System.Drawing.Graphics.Dispose()

Here are the examples of the csharp api System.Drawing.Graphics.Dispose() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

521 Examples 7

19 Source : momiji_base.cs
with BSD 2-Clause "Simplified" License
from chengse66

protected static Image generate_pattern(int size)
	{
		Image image = new Bitmap(size * 2, size * 2);
		Graphics graphics = Graphics.FromImage(image);

		graphics.FillRectangles(Brushes.LightGray, new Rectangle[]
				{
					new Rectangle(0, 0, size, size),
					new Rectangle(size, size, size, size),
				});

		graphics.FillRectangles(Brushes.White, new Rectangle[]
				{
					new Rectangle(0, size, size, size),
					new Rectangle(size, 0, size, size),
				});

		graphics.Dispose();

		return image;
	}

19 Source : palette.cs
with BSD 2-Clause "Simplified" License
from chengse66

private void generate_gradient_wheel()
		{
			Color[] colors;
			Region region;
			PathGradientBrush brush;
			GraphicsPath path = new GraphicsPath();
			GraphicsPath ellipse = new GraphicsPath();
			Graphics graphics = Graphics.FromImage(wheel);
			int diameter = wheel.Width;
			int inscribe = diameter / 10;

			--diameter;

			path.AddEllipse(0, 0, diameter, diameter);
			ellipse.AddEllipse(inscribe, inscribe, diameter - inscribe * 2, diameter - inscribe * 2);

			path.Flatten();

			region = new Region(ellipse);
			brush = new PathGradientBrush(path);
			colors = new Color[path.PointCount];

			for (int index = 0; index < path.PointCount; ++index)
			{
				double angle = (double)index / path.PointCount + 0.375/*135.0 / 180.0*/;

				if (.0 > angle)
					angle = angle + 1.0;
				else if (1.0 <= angle)
					angle = angle - 1.0;

				colors[index] = hsv.hsv_2_rgb(angle, 1.0, 1.0);
			}

			brush.SurroundColors = colors;

			graphics.SetClip(region, CombineMode.Exclude);

			graphics.FillEllipse(brush, 0, 0, diameter, diameter);

			graphics.SmoothingMode = SmoothingMode.AntiAlias;

			graphics.DrawEllipse(SystemPens.Control, 0, 0, diameter, diameter);
			graphics.DrawPath(SystemPens.Control, ellipse);

			graphics.Dispose();
			region.Dispose();
			brush.Dispose();
			ellipse.Dispose();
			path.Dispose();
		}

19 Source : palette.cs
with BSD 2-Clause "Simplified" License
from chengse66

unsafe private void generate_gradient_triangle()
		{
			double vsh;
			Graphics graphics;
			PointF hue, saturation, value;
			BitmapData data = triangle.LockBits(new Rectangle(Point.Empty, triangle.Size), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
			int* pixels = (int*)data.Scan0;

			compute_triangle(out hue, out saturation, out value);

			vsh = vector_cross(value, saturation, hue);

			for (int y = 0; y < triangle.Height; ++y)
				for (int x = 0; x < triangle.Width; ++x)
				{
					Point point = new Point(x, y);

					*pixels++ = compute_color(vsh,
						vector_cross(value, saturation, point),
						vector_cross(hue, value, point),
						vector_cross(saturation, hue, point), false);
				}

			triangle.UnlockBits(data);

			graphics = Graphics.FromImage(triangle);

			graphics.SmoothingMode = SmoothingMode.AntiAlias;

			graphics.DrawPolygon(SystemPens.Control, new PointF[] { hue, saturation, value, });

			graphics.Dispose();
		}

19 Source : palette.cs
with BSD 2-Clause "Simplified" License
from chengse66

private void paint(object o, PaintEventArgs e)
		{
			IntPtr hdc;
			Bitmap bitmap = new Bitmap(Width, Height);
			Graphics graphics = Graphics.FromImage(bitmap);

			graphics.DrawImage(wheel, PointF.Empty);
			graphics.DrawImage(triangle, (float)(wheel.Width / 10.0), (float)(wheel.Width / 10.0));

			graphics.Dispose();

			e.Graphics.DrawImage(bitmap, Point.Empty);

			hdc = e.Graphics.GetHdc();

			draw_ellipse(rotate_point((wheel.Width - 1.0) / 2.0 - wheel.Width / 20.0, .0, wheel.Width / 2.0, 0), hdc);
			draw_ellipse(compute_point(), hdc);

			e.Graphics.ReleaseHdc();

			bitmap.Dispose();
		}

19 Source : palette.cs
with BSD 2-Clause "Simplified" License
from chengse66

private void update_gradient_front(Color[] colors)
		{
			float[] positions = new float[colors.Length];
			Graphics graphics = Graphics.FromImage(image);
			Rectangle rectangle = new Rectangle(Point.Empty, image.Size);
			LinearGradientBrush brush = new LinearGradientBrush(rectangle, Color.Transparent, Color.Transparent, .0f);
			ColorBlend blend = new ColorBlend();

			for (int index = 0; index < positions.Length; ++index)
				positions[index] = index / (positions.Length - 1.0f);

			blend.Colors = colors;
			blend.Positions = positions;

			brush.InterpolationColors = blend;

			graphics.FillRectangle(brush, rectangle);

			graphics.Dispose();
			brush.Dispose();

			Refresh();
		}

19 Source : palette.cs
with BSD 2-Clause "Simplified" License
from chengse66

internal void update_gradient(Color[] colors)
		{
			TextureBrush texture = generate_pattern_brush((Height - 9) / 2);
			Graphics graphics = Graphics.FromImage(image);

			graphics.FillRectangle(texture, new Rectangle(Point.Empty, image.Size));

			graphics.Dispose();
			texture.Dispose();

			update_gradient_front(colors);
		}

19 Source : palette.cs
with BSD 2-Clause "Simplified" License
from chengse66

private void paint(object o, PaintEventArgs e)
		{
			Pen triangle;
			Bitmap bitmap = new Bitmap(Width, Height);
			Graphics graphics = Graphics.FromImage(bitmap);
			int position = (int)(value * (Width - 41.0) / maximum);

			graphics.Clear(BackColor);

			draw_border(hovered, new Rectangle(1, 0, Width - 36, Height - 5), graphics);

			if (hovered)
				triangle = new Pen(Color.FromArgb(0xc3, 0x76, 0x3d));
			else
				triangle = new Pen(Color.FromArgb(0x73, 0x73, 0x73));

			graphics.DrawPolygon(triangle, new Point[] { new Point(position + 3, Height - 5), new Point(position + 6, Height - 2), new Point(position + 6, Height - 1), new Point(position, Height - 1), new Point(position, Height - 2), });

			graphics.DrawString(text, Font, SystemBrushes.ControlText, Width - 35, 0);

			if (null != image)
				graphics.DrawImage(image, 3, 2, Width - 40, Height - 9);

			graphics.Dispose();
			triangle.Dispose();

			e.Graphics.DrawImage(bitmap, 0, 0);

			bitmap.Dispose();
		}

19 Source : palette.cs
with BSD 2-Clause "Simplified" License
from chengse66

private void paint(object o, PaintEventArgs e)
		{
			int size = Height - 4;
			TextureBrush texture = generate_pattern_brush(size / 2);
			Bitmap bitmap = new Bitmap(Width, Height);
			Graphics graphics = Graphics.FromImage(bitmap);

			draw_border(hovered, new Rectangle(0, 0, Width, Height), e.Graphics);

			texture.TranslateTransform(2.0f, 2.0f);

			graphics.FillRectangle(texture, 2, 2, Width - 4, size);

			for (int index = 0; index < count; ++index)
			{
				SolidBrush brush = new SolidBrush(colors[index]);

				graphics.FillRectangle(brush, 2 + size * index, 2, size, size);

				brush.Dispose();
			}

			graphics.Dispose();
			texture.Dispose();

			e.Graphics.DrawImage(bitmap, 0, 0);

			bitmap.Dispose();
		}

19 Source : palette.cs
with BSD 2-Clause "Simplified" License
from chengse66

private void paint(object o, PaintEventArgs e)
		{
			int size = Height - 4;
			TextureBrush texture = generate_pattern_brush(size / 2);
			Brush elder = new SolidBrush(color_elder);
			Brush current = new SolidBrush(color_current);
			Bitmap bitmap = new Bitmap(Width, Height);
			Graphics graphics = Graphics.FromImage(bitmap);

			draw_border(hovered, new Rectangle(0, 0, Width, Height), e.Graphics);

			texture.TranslateTransform(2.0f, 2.0f);

			graphics.FillRectangle(texture, 2, 2, Width - 4, size);

			graphics.FillRectangle(elder, 2, 2, size, size);
			graphics.FillRectangle(current, size + 2, 2, size, size);

			graphics.Dispose();
			texture.Dispose();
			elder.Dispose();
			current.Dispose();

			e.Graphics.DrawImage(bitmap, 0, 0);

			bitmap.Dispose();
		}

19 Source : preferences.cs
with BSD 2-Clause "Simplified" License
from chengse66

private void update_image(Button button)
	{
		Image image = generate_pattern(8);
		Graphics graphics = Graphics.FromImage(image);
		SolidBrush brush = new SolidBrush((Color)button.Tag);

		graphics.FillRectangle(brush, 0, 0, image.Width, image.Height);

		graphics.Dispose();

		if (null != button.Image)
			button.Image.Dispose();

		button.Image = image;
	}

19 Source : VerifyHelper.cs
with GNU General Public License v3.0
from chenyinxin

private static Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)
        {
            double PI = 6.283185307179586476925286766559;
            Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height);
            Graphics graph = Graphics.FromImage(destBmp);
            graph.FillRectangle(new SolidBrush(Color.White), 0, 0, destBmp.Width, destBmp.Height);
            graph.Dispose();
            double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width;
            for (int i = 0; i < destBmp.Width; i++)
            {
                for (int j = 0; j < destBmp.Height; j++)
                {
                    double dx = 0;
                    dx = bXDir ? (PI * (double)j) / dBaseAxisLen : (PI * (double)i) / dBaseAxisLen;
                    dx += dPhase;
                    double dy = Math.Sin(dx);
                    int nOldX = 0, nOldY = 0;
                    nOldX = bXDir ? i + (int)(dy * dMultValue) : i;
                    nOldY = bXDir ? j : j + (int)(dy * dMultValue);

                    Color color = srcBmp.GetPixel(i, j);
                    if (nOldX >= 0 && nOldX < destBmp.Width
                     && nOldY >= 0 && nOldY < destBmp.Height)
                    {
                        destBmp.SetPixel(nOldX, nOldY, color);
                    }
                }
            }
            srcBmp.Dispose();
            return destBmp;
        }

19 Source : TextView.cs
with MIT License
from codewitch-honey-crisis

public int GetDrawingXPos(int logicalLine, int logicalColumn)
		{
			List<FoldMarker> foldings = Doreplacedent.FoldingManager.GetTopLevelFoldedFoldings();
			int i;
			FoldMarker f = null;
			// search the last folding that's interresting
			for (i = foldings.Count - 1; i >= 0; --i) {
				f = foldings[i];
				if (f.StartLine < logicalLine || f.StartLine == logicalLine && f.StartColumn < logicalColumn) {
					break;
				}
				FoldMarker f2 = foldings[i / 2];
				if (f2.StartLine > logicalLine || f2.StartLine == logicalLine && f2.StartColumn >= logicalColumn) {
					i /= 2;
				}
			}
			int lastFolding  = 0;
			int firstFolding = 0;
			int column       = 0;
			int tabIndent    = Doreplacedent.TextEditorProperties.TabIndent;
			float drawingPos;
			Graphics g = textArea.CreateGraphics();
			// if no folding is interresting
			if (f == null || !(f.StartLine < logicalLine || f.StartLine == logicalLine && f.StartColumn < logicalColumn)) {
				drawingPos = CountColumns(ref column, 0, logicalColumn, logicalLine, g);
				return (int)(drawingPos - textArea.VirtualTop.X);
			}
			
			// if logicalLine/logicalColumn is in folding
			if (f.EndLine > logicalLine || f.EndLine == logicalLine && f.EndColumn > logicalColumn) {
				logicalColumn = f.StartColumn;
				logicalLine = f.StartLine;
				--i;
			}
			lastFolding = i;
			
			// search backwards until a new visible line is reched
			for (; i >= 0; --i) {
				f = (FoldMarker)foldings[i];
				if (f.EndLine < logicalLine) { // reached the begin of a new visible line
					break;
				}
			}
			firstFolding = i + 1;
			
			if (lastFolding < firstFolding) {
				drawingPos = CountColumns(ref column, 0, logicalColumn, logicalLine, g);
				return (int)(drawingPos - textArea.VirtualTop.X);
			}
			
			int foldEnd      = 0;
			drawingPos = 0;
			for (i = firstFolding; i <= lastFolding; ++i) {
				f = foldings[i];
				drawingPos += CountColumns(ref column, foldEnd, f.StartColumn, f.StartLine, g);
				foldEnd = f.EndColumn;
				column += f.FoldText.Length;
				drawingPos += additionalFoldTextSize;
				drawingPos += MeasureStringWidth(g, f.FoldText, TextEditorProperties.FontContainer.RegularFont);
			}
			drawingPos += CountColumns(ref column, foldEnd, logicalColumn, logicalLine, g);
			g.Dispose();
			return (int)(drawingPos - textArea.VirtualTop.X);
		}

19 Source : ImgVerifyCodeHelper.cs
with Apache License 2.0
from Coldairarrow

public byte[] CreateValidateGraphic(string validateCode, float fontsize, int height)
            {
                Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * (fontsize + 1)), height);
                Graphics g = Graphics.FromImage(image);
                try
                {
                    //生成随机生成器     
                    Random random = new Random();
                    //清空图片背景色     
                    g.Clear(Color.White);
                    //画图片的干扰线     
                    for (int i = 0; i < 25; i++)
                    {
                        int x1 = random.Next(image.Width);
                        int x2 = random.Next(image.Width);
                        int y1 = random.Next(image.Height);
                        int y2 = random.Next(image.Height);
                        g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                    }
                    //画图片验证码
                    Rectangle layoutRectange = new Rectangle(0, 0, image.Width, image.Height);
                    Font font = new Font("Arial", fontsize, (FontStyle.Bold | FontStyle.Italic));
                    LinearGradientBrush brush = new LinearGradientBrush(layoutRectange, Color.Blue, Color.DarkRed, 1.2f, true);
                    StringFormat format = new StringFormat() { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center };
                    g.DrawString(validateCode, font, brush, layoutRectange, format);

                    //画图片的前景干扰点     
                    for (int i = 0; i < 100; i++)
                    {
                        int x = random.Next(image.Width);
                        int y = random.Next(image.Height);
                        image.SetPixel(x, y, Color.FromArgb(random.Next()));
                    }
                    //画图片的边框线     
                    g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                    //保存图片数据     
                    MemoryStream stream = new MemoryStream();
                    image.Save(stream, ImageFormat.Jpeg);
                    //输出图片流     
                    return stream.ToArray();
                }
                finally
                {
                    g.Dispose();
                    image.Dispose();
                }
            }

19 Source : LyricsRenderer.cs
with Apache License 2.0
from cqjjjzr

public static Bitmap Render2LineLyrics(string line1, string line2)
        {
            var line1Bitmap = RenderLyrics(line1, _mainFont);
            var line2Bitmap = RenderLyrics(line2, _subFont);
            var bitmap = new Bitmap(Math.Max(line1Bitmap.Width, line2Bitmap.Width), line1Bitmap.Height + line2Bitmap.Height);
            var g = Graphics.FromImage(bitmap);
            g.DrawImage(line1Bitmap, new PointF(0, 0));
            g.DrawImage(line2Bitmap, new PointF(0, line1Bitmap.Height * 0.8f));
            g.Dispose();
            line1Bitmap.Dispose();
            line2Bitmap.Dispose();
            return bitmap;
        }

19 Source : LyricsRenderer.cs
with Apache License 2.0
from cqjjjzr

public static Bitmap RenderLyrics(string lyric, Font font)
        {
            var fontBounds = TextRenderer.MeasureText(lyric, font);
            var height = fontBounds.Height;
            if (height <= 0) height = 1;
            var width = fontBounds.Width;
            if (width <= 0) width = 1;
            var bitmap = new Bitmap(_width, height);
            var g = Graphics.FromImage(bitmap);
            g.InterpolationMode = InterpolationMode.High;
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
            g.CompositingQuality = CompositingQuality.HighQuality;

            var dstRect = new RectangleF(
                ((float)_width - fontBounds.Width) / 2,
                0,
                width,
                height);
            if (dstRect.X < 0) dstRect.X = 0;
            if (dstRect.Width > _width) dstRect.Width = _width;

            //using (Image shadow = GaussianHelper.CreateShadow())
            //
            var fontEmSize = font.Size;
            var layoutRect = new RectangleF(dstRect.X - ShadowOffset, dstRect.Y - ShadowOffset, dstRect.Width, dstRect.Height);
            var shadowPath = new GraphicsPath(FillMode.Alternate);
            shadowPath.AddString(lyric, font.FontFamily, (int)font.Style, fontEmSize, layoutRect, Format);
            g.FillPath(ShadowBrush, shadowPath);
            shadowPath.Dispose();

            var stringPath = new GraphicsPath(FillMode.Alternate);
            stringPath.AddString(lyric, font.FontFamily, (int)font.Style, fontEmSize, dstRect, Format);
            if (_borderPen != null)
                g.DrawPath(_borderPen, stringPath);
            var stringBrush = CreateGradientBrush(dstRect);
            g.FillPath(stringBrush, stringPath);
            //g.DrawString(lyric, _mainFont, stringBrush, dstRect);
            g.Dispose();
            stringBrush.Dispose();
            stringPath.Dispose();
            return bitmap;
        }

19 Source : Form1.cs
with MIT License
from ctsecurity

public void startListening()
        {
            try
            {
                listener = new TcpListener(port);
                listener.Start();
                mainSocket = listener.AcceptSocket();
                s = new NetworkStream(mainSocket);
                evenreplacedcher = new Thread(new ThreadStart(waitForKeys));
                evenreplacedcher.Start();
                while (true)
                {
                    Bitmap screeny = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
                    Graphics theShot = Graphics.FromImage(screeny);
                    theShot.ScaleTransform(.25F, .25F);
                    theShot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
                    BinaryFormatter bFormat = new BinaryFormatter();
                    bFormat.Serialize(s, screeny);
                    //screeny.Save(s,ImageFormat.Png);
                    Thread.Sleep(imageDelay);
                    theShot.Dispose();
                    screeny.Dispose();
                }
            }
            catch (Exception)
            {
                if (mainSocket.IsBound)
                    mainSocket.Close();
                if (listener != null)
                    listener.Stop();
                //MessageBox.Show(gay.ToString());
            }
        }

19 Source : PixDocumentHandler.cs
with MIT License
from cwensley

public override void UpdateZoom()
		{
			int zoom = Loader.ZoomPercent;
			if (Viewer != null)
			{
				Graphics gscreen = Viewer.CreateGraphics();
				charSize = Size.Round(gscreen.MeasureString("a", font));
				gscreen.Dispose();
			}
			else
				charSize = new Size(8, font.Height);

			if (Viewer != null && zoom == -1)
			{
				int width = Viewer.ClientSize.Width;
				if (width < 50) width = 50;
				int height = width * DrawSize.Height / DrawSize.Width;
				drawSize = new Size(width, height); 
			}
			else
			{
				int width = (DrawSize.Width * zoom / 100);
				int height = width * DrawSize.Height / DrawSize.Width;
				drawSize = new Size(width, height); 
			}
			if (drawImage == null || drawSize != drawImage.Size)
			{
				if (drawImage != null) 
				{
					drawImage.Dispose();
					drawImage = null;
				}

				if (drawSize.Width != 0 && drawSize.Height != 0)
				{
					if (Viewer != null)
					{
						// if viewing from the viewer, create compatible bitmap so it goes faster
						Graphics gscreen = Viewer.CreateGraphics();
						drawImage = new Bitmap(drawSize.Width, drawSize.Height, gscreen);
						gscreen.Dispose();
					}
					else drawImage = new Bitmap(drawSize.Width, drawSize.Height, PixelFormat.Format32bppArgb);
					Graphics g = Graphics.FromImage(drawImage);

					Bitmap b = new Bitmap(DrawSize.Width, DrawSize.Height, PixelFormat.Format32bppArgb);
					Graphics gImg = Graphics.FromImage(b);
					DrawIt(gImg);
					gImg.Dispose();
					g.InterpolationMode = Loader.Quality; 
					g.DrawImage(b, 0,0, drawSize.Width, drawSize.Height);
					g.Dispose();
					b.Dispose();
				}
			}

			if (Viewer != null) 
			{
				Viewer.AutoScrollMinSize = drawSize;
				adjust.Width = (Viewer.AutoScrollMinSize.Width < Viewer.ClientSize.Width) ? ((Viewer.ClientSize.Width - Viewer.AutoScrollMinSize.Width) / 2) : 0; 
				adjust.Height = (Viewer.AutoScrollMinSize.Height < Viewer.ClientSize.Height) ? ((Viewer.ClientSize.Height - Viewer.AutoScrollMinSize.Height) / 2) : 0; 
			}
			base.UpdateZoom ();
		}

19 Source : BitmapProcess.cs
with GNU General Public License v3.0
from cymheart

static public void BoxShadow(Bitmap processBitmap, int shadowRadius, int[] cornersType, int[] cornersRadius)
        {
            int r = shadowRadius;
            int sideWidth = shadowRadius;
            int offset = 2;

            Graphics g;
            Bitmap bitmap;
            Rectangle rc;
            Rectangle rc1;
            Bitmap effectBitmap;
            GraphicsPath path;
            GaussianBlur gs = new GaussianBlur(r);

            int width = processBitmap.Width;
            int height = processBitmap.Height;
            Graphics baseg = Graphics.FromImage(processBitmap);

            //
            int leftTopWidth = sideWidth + r;
            int leftTopHeight = sideWidth + r;
            bitmap = new Bitmap(leftTopWidth, leftTopHeight);
            g = Graphics.FromImage(bitmap);
            rc = new Rectangle(sideWidth, sideWidth, r, r);

            if (cornersType[0] == 0)
            {
                g.FillRectangle(Brushes.Black, rc);
                effectBitmap = gs.ProcessImage(bitmap);
                baseg.DrawImage(effectBitmap, 0, 0, new Rectangle(0, 0, sideWidth, sideWidth), GraphicsUnit.Pixel);
            }
            else
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                path = DrawUtils.CreateRoundedRectanglePath(rc, cornersRadius[0]);
                g.FillPath(Brushes.Black, path);
                path.Dispose();
                effectBitmap = gs.ProcessImage(bitmap);
                baseg.DrawImage(effectBitmap, 0, 0, new Rectangle(0, 0, sideWidth, sideWidth), GraphicsUnit.Pixel);
                baseg.DrawImage(effectBitmap, sideWidth, sideWidth, new Rectangle(sideWidth, sideWidth, r, r), GraphicsUnit.Pixel);
            }

            g.Dispose();
            bitmap.Dispose();


            ////
            int rightTopWidth = sideWidth + r;
            int rightTopHeight = sideWidth + r;
            bitmap = new Bitmap(rightTopWidth, rightTopHeight);
            g = Graphics.FromImage(bitmap);
            rc = new Rectangle(0, sideWidth, r, r);

            if (cornersType[0] == 0)
            {
                g.FillRectangle(Brushes.Black, rc);
                effectBitmap = gs.ProcessImage(bitmap);
                baseg.DrawImage(effectBitmap, width - sideWidth, 0, new Rectangle(rightTopWidth - sideWidth, 0, sideWidth, sideWidth), GraphicsUnit.Pixel);
            }
            else
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                path = DrawUtils.CreateRoundedRectanglePath(rc, cornersRadius[0]);
                g.FillPath(Brushes.Black, path);
                path.Dispose();
                effectBitmap = gs.ProcessImage(bitmap);
                baseg.DrawImage(effectBitmap, width - sideWidth, 0, new Rectangle(rightTopWidth - sideWidth, 0, sideWidth, sideWidth), GraphicsUnit.Pixel);
                baseg.DrawImage(effectBitmap, width - sideWidth - r, sideWidth, new Rectangle(0, sideWidth, r, r), GraphicsUnit.Pixel);
            }
            g.Dispose();
            bitmap.Dispose();

            ////
            int leftBottomWidth = sideWidth + r;
            int leftBottomHeight = sideWidth + r;
            bitmap = new Bitmap(leftBottomWidth, leftBottomHeight);
            g = Graphics.FromImage(bitmap);
            rc = new Rectangle(sideWidth, 0, r, r);

            if (cornersType[2] == 0)
            {
                g.FillRectangle(Brushes.Black, rc);
                effectBitmap = gs.ProcessImage(bitmap);
                baseg.DrawImage(effectBitmap, 0, height - sideWidth, new Rectangle(0, leftBottomHeight - sideWidth, sideWidth, sideWidth), GraphicsUnit.Pixel);
            }
            else
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                path = DrawUtils.CreateRoundedRectanglePath(rc, cornersRadius[0]);
                g.FillPath(Brushes.Black, path);
                path.Dispose();
                effectBitmap = gs.ProcessImage(bitmap);
                baseg.DrawImage(effectBitmap, 0, height - sideWidth, new Rectangle(0, leftBottomHeight - sideWidth, sideWidth, sideWidth), GraphicsUnit.Pixel);
                baseg.DrawImage(effectBitmap, sideWidth, height - sideWidth - r, new Rectangle(sideWidth, 0, r, r), GraphicsUnit.Pixel);
            }

            g.Dispose();
            bitmap.Dispose();

            ////
            int rightBottomWidth = sideWidth + r;
            int rightBottomHeight = sideWidth + r;
            bitmap = new Bitmap(rightBottomWidth, rightBottomHeight);
            g = Graphics.FromImage(bitmap);
            rc = new Rectangle(0, 0, r, r);

            if (cornersType[3] == 0)
            {
                g.FillRectangle(Brushes.Black, rc);
                effectBitmap = gs.ProcessImage(bitmap);
                baseg.DrawImage(effectBitmap, width - sideWidth, height - sideWidth, new Rectangle(rightBottomHeight - sideWidth, rightBottomHeight - sideWidth, sideWidth, sideWidth), GraphicsUnit.Pixel);
            }
            else
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                path = DrawUtils.CreateRoundedRectanglePath(rc, cornersRadius[0]);
                g.FillPath(Brushes.Black, path);
                path.Dispose();
                effectBitmap = gs.ProcessImage(bitmap);
                baseg.DrawImage(effectBitmap, width - sideWidth, height - sideWidth, new Rectangle(rightBottomHeight - sideWidth, rightBottomHeight - sideWidth, sideWidth, sideWidth), GraphicsUnit.Pixel);
                baseg.DrawImage(effectBitmap, width - sideWidth - r, height - sideWidth - r, new Rectangle(0, 0, r, r), GraphicsUnit.Pixel);
            }

            g.Dispose();
            bitmap.Dispose();


            ////
            int topWidth = width;
            int topHeight = r + sideWidth;
            bitmap = new Bitmap(topWidth, topHeight);
            g = Graphics.FromImage(bitmap);
            rc = new Rectangle(sideWidth, sideWidth, width - sideWidth * 2, r);

            if (cornersType[0] == 1)
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                rc1 = new Rectangle(rc.X, rc.Y, rc.Width / 2 + offset, rc.Height );
                path = DrawUtils.CreateRoundedRectanglePath(rc1, cornersRadius[0]);
                g.FillPath(Brushes.Black, path);
            }
            else
            {
                rc1 = new Rectangle(rc.X, rc.Y, rc.Width / 2 + offset, rc.Height);
                g.FillRectangle(Brushes.Black, rc1);
            }


            if (cornersType[1] == 1)
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                rc1 = new Rectangle(rc.Right - rc.Width /2 - offset, rc.Y, rc.Width / 2 + offset, rc.Height);
                path = DrawUtils.CreateRoundedRectanglePath(rc1, cornersRadius[1]);
                g.FillPath(Brushes.Black, path);
            }
            else
            {
                rc1 = new Rectangle(rc.Right - rc.Width / 2 - offset, rc.Y, rc.Width / 2 + offset, rc.Height);
                g.FillRectangle(Brushes.Black, rc1);
            }

            effectBitmap = gs.ProcessImage(bitmap);
            baseg.DrawImage(effectBitmap, sideWidth, 0, new Rectangle(sideWidth, 0, topWidth - sideWidth * 2, sideWidth), GraphicsUnit.Pixel);
            g.Dispose();
            bitmap.Dispose();

            ////
            int bottomWidth = width;
            int bottomHeight = r + sideWidth;
            bitmap = new Bitmap(bottomWidth, bottomHeight);
            g = Graphics.FromImage(bitmap);
            rc = new Rectangle(sideWidth, 0, bottomWidth - 2 * sideWidth, r);

            if (cornersType[2] == 1)
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                rc1 = new Rectangle(rc.X, rc.Y, rc.Width / 2 + offset, rc.Height);
                path = DrawUtils.CreateRoundedRectanglePath(rc1, cornersRadius[0]);
                g.FillPath(Brushes.Black, path);
            }
            else
            {
                rc1 = new Rectangle(rc.X, rc.Y, rc.Width / 2 + offset, rc.Height);
                g.FillRectangle(Brushes.Black, rc1);
            }


            if (cornersType[3] == 1)
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                rc1 = new Rectangle(rc.Right - rc.Width / 2 - offset, rc.Y, rc.Width / 2 + offset, rc.Height);
                path = DrawUtils.CreateRoundedRectanglePath(rc1, cornersRadius[1]);
                g.FillPath(Brushes.Black, path);
            }
            else
            {
                rc1 = new Rectangle(rc.Right - rc.Width / 2 - offset, rc.Y, rc.Width / 2 + offset, rc.Height);
                g.FillRectangle(Brushes.Black, rc1);
            }

            effectBitmap = gs.ProcessImage(bitmap);
            baseg.DrawImage(effectBitmap, sideWidth, height - sideWidth, new Rectangle(sideWidth, bottomHeight - sideWidth, bottomWidth - sideWidth * 2, sideWidth), GraphicsUnit.Pixel);
            g.Dispose();
            bitmap.Dispose();

            ////
            int leftWidth = sideWidth + r;
            int leftHeight = height;
            bitmap = new Bitmap(leftWidth, leftHeight);
            g = Graphics.FromImage(bitmap);
            rc = new Rectangle(sideWidth, sideWidth, r, leftHeight - sideWidth * 2);

            if (cornersType[0] == 1)
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                rc1 = new Rectangle(rc.X, rc.Y, rc.Width, rc.Height / 2 + offset);
                path = DrawUtils.CreateRoundedRectanglePath(rc1, cornersRadius[0]);
                g.FillPath(Brushes.Black, path);
            }
            else
            {
                rc1 = new Rectangle(rc.X, rc.Y, rc.Width, rc.Height / 2 + offset);
                g.FillRectangle(Brushes.Black, rc1);
            }


            if (cornersType[2] == 1)
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                rc1 = new Rectangle(rc.X, rc.Bottom - rc.Height / 2 - offset, rc.Width , rc.Height /2 + offset);
                path = DrawUtils.CreateRoundedRectanglePath(rc1, cornersRadius[2]);
                g.FillPath(Brushes.Black, path);
            }
            else
            {
                rc1 = new Rectangle(rc.X, rc.Bottom - rc.Height / 2 - offset, rc.Width, rc.Height / 2 + offset);
                g.FillRectangle(Brushes.Black, rc1);
            }

            effectBitmap = gs.ProcessImage(bitmap);
            baseg.DrawImage(effectBitmap, 0, sideWidth, new Rectangle(0, sideWidth, sideWidth, leftHeight - sideWidth * 2), GraphicsUnit.Pixel);
            g.Dispose();
            bitmap.Dispose();

            ////
            int rightWidth = sideWidth + r;
            int rightHeight = height;
            bitmap = new Bitmap(leftWidth, leftHeight);
            g = Graphics.FromImage(bitmap);
            rc = new Rectangle(0, sideWidth, r, rightHeight - sideWidth * 2);


            if (cornersType[1] == 1)
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                rc1 = new Rectangle(rc.X, rc.Y, rc.Width, rc.Height / 2 + offset);
                path = DrawUtils.CreateRoundedRectanglePath(rc1, cornersRadius[1]);
                g.FillPath(Brushes.Black, path);
            }
            else
            {
                rc1 = new Rectangle(rc.X, rc.Y, rc.Width, rc.Height / 2 + offset);
                g.FillRectangle(Brushes.Black, rc1);
            }


            if (cornersType[3] == 1)
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                rc1 = new Rectangle(rc.X, rc.Bottom - rc.Height / 2 - offset, rc.Width, rc.Height / 2 + offset);
                path = DrawUtils.CreateRoundedRectanglePath(rc1, cornersRadius[3]);
                g.FillPath(Brushes.Black, path);
            }
            else
            {
                rc1 = new Rectangle(rc.X, rc.Bottom - rc.Height / 2 - offset, rc.Width, rc.Height / 2 + offset);
                g.FillRectangle(Brushes.Black, rc1);
            }

            effectBitmap = gs.ProcessImage(bitmap);
            baseg.DrawImage(effectBitmap, width - sideWidth, sideWidth, new Rectangle(leftWidth - sideWidth, sideWidth, sideWidth, leftHeight - sideWidth * 2), GraphicsUnit.Pixel);
            g.Dispose();
            bitmap.Dispose();

            baseg.Dispose();
        }

19 Source : D2DGraphics.cs
with GNU General Public License v3.0
from cymheart

public void RelaseGdiGraphics(Graphics gdiGraphics)
        {
            gdiRenderTarget.ReleaseDC();
            gdiGraphics.Dispose();
        }

19 Source : AnimatedGifEncoder.cs
with MIT License
from d-mod

protected void GetImagePixels() {
            var w = image.Width;
            var h = image.Height;
            //		int type = image.GetType().;
            if (w != width
                || h != height
            ) {
                // create new image with right size/format
                Image temp =
                    new Bitmap(width, height);
                var g = Graphics.FromImage(temp);
                g.DrawImage(image, 0, 0);
                image = temp;
                g.Dispose();
            }
            /*
				ToDo:
				improve performance: use unsafe code 
			*/
            pixels = new byte[3 * image.Width * image.Height];
            var tempBitmap = new Bitmap(image);
            var data = tempBitmap.ToArray();
            var len = image.Width * image.Height;
            for (var i = 0; i < len; i++) {
                pixels[i * 3 + 0] = data[i * 4 + 2];
                pixels[i * 3 + 1] = data[i * 4 + 1];
                pixels[i * 3 + 2] = data[i * 4 + 0];
            }

            //		pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
        }

19 Source : GifDecoder.cs
with MIT License
from d-mod

protected void SetPixels() {
            // expose destination image's pixels as int array
            //		int[] dest =
            //			(( int ) image.getRaster().getDataBuffer()).getData();
            var dest = GetPixels(bitmap);

            // fill in starting image contents based on last image's dispose code
            if (lastDispose > 0) {
                if (lastDispose == 3) {
                    // use image before last
                    var n = frameCount - 2;
                    if (n > 0) {
                        lastImage = GetFrame(n - 1);
                    } else {
                        lastImage = null;
                    }
                }

                if (lastImage != null) {
                    //				int[] prev =
                    //					((DataBufferInt) lastImage.getRaster().getDataBuffer()).getData();
                    var prev = GetPixels(new Bitmap(lastImage));
                    Array.Copy(prev, 0, dest, 0, width * height);
                    // copy pixels

                    if (lastDispose == 2) {
                        // fill last image rect area with background color
                        var g = Graphics.FromImage(image);
                        var c = Color.Empty;
                        if (transparency) {
                            c = Color.FromArgb(0, 0, 0, 0); // replacedume background is transparent
                        } else {
                            c = Color.FromArgb(lastBgColor);
                        }
                        var brush = new SolidBrush(c);
                        g.FillRectangle(brush, lastRect);
                        brush.Dispose();
                        g.Dispose();
                    }
                }
            }

            // copy each source line to the appropriate place in the destination
            var preplaced = 1;
            var inc = 8;
            var iline = 0;
            for (var i = 0; i < ih; i++) {
                var line = i;
                if (interlace) {
                    if (iline >= ih) {
                        preplaced++;
                        switch (preplaced) {
                            case 2:
                                iline = 4;
                                break;
                            case 3:
                                iline = 2;
                                inc = 4;
                                break;
                            case 4:
                                iline = 1;
                                inc = 2;
                                break;
                        }
                    }
                    line = iline;
                    iline += inc;
                }
                line += iy;
                if (line < height) {
                    var k = line * width;
                    var dx = k + ix; // start of line in dest
                    var dlim = dx + iw; // end of dest line
                    if (k + width < dlim) dlim = k + width; // past dest edge
                    var sx = i * iw; // start of line in source
                    while (dx < dlim) {
                        // map color and insert in destination
                        var index = pixels[sx++] & 0xff;
                        var c = act[index];
                        if (c != 0) dest[dx] = c;
                        dx++;
                    }
                }
            }
            SetPixels(dest);
        }

19 Source : Bitmaps.cs
with MIT License
from d-mod

public static Bitmap Trim(this Bitmap bmp) {
            var rct = bmp.Scan();
            var image = new Bitmap(rct.Width, rct.Height);
            var g = Graphics.FromImage(image);
            var empty = new Rectangle(Point.Empty, rct.Size);
            g.DrawImage(bmp, empty, rct, GraphicsUnit.Pixel);
            g.Dispose();
            return image;
        }

19 Source : Sprite.cs
with MIT License
from d-mod

public void TrimImage() {
            if (Type == ColorBits.LINK || CompressMode == CompressMode.NONE) {
                return;
            }
            if (Picture == null) {
                return;
            }
            var rct = Picture.Scan();
            var image = new Bitmap(rct.Width, rct.Height);
            var g = Graphics.FromImage(image);
            var empty = new Rectangle(Point.Empty, rct.Size);
            g.DrawImage(Picture, empty, rct, GraphicsUnit.Pixel);
            g.Dispose();
            Size = rct.Size;
            Location = Location.Add(rct.Location);
            Picture = image;
        }

19 Source : Avatars.cs
with MIT License
from d-mod

public static Bitmap Preview(Album[] array, int index) {

            var x = 800;
            var y = 600;
            var width = 1;
            var height = 1;
            foreach (var al in array) {
                if (index >= al.List.Count) {
                    continue;
                }
                var source = al.List[index];
                if (source.Type == ColorBits.LINK) {
                    source = source.Target;
                }
                if (source.Hidden) {
                    continue;
                }
                if (source.Width + source.X > width) {
                    width = source.Width + source.X;
                }
                if (source.Height + source.Y > height) {
                    height = source.Height + source.Y;
                }
                if (source.X < x) {
                    x = source.X;
                }
                if (source.Y < y) {
                    y = source.Y;
                }
            }
            width -= x;
            height -= y;
            width = Math.Max(1,width); //防止宽高小于1
            height = Math.Max(1, height);
            var bmp = new Bitmap(width, height);
            var g = Graphics.FromImage(bmp);
            foreach (var img in array) {
                if (index > img.List.Count - 1) {
                    continue;
                }
                var source = img[index];
                if (source.Type == ColorBits.LINK) {
                    source = source.Target;
                }
                if (source.CompressMode == CompressMode.NONE && source.Width * source.Height == 1) {
                    continue;
                }
                g.DrawImage(source.Picture, source.X - x, source.Y - y);
            }
            g.Dispose();
            return bmp;
        }

19 Source : BufferedPaint.cs
with Apache License 2.0
from dahall

protected override void Dispose(bool disposing)
			{
				if (disposing)
				{
					SourceGraphics?.Dispose();
					Graphics?.Dispose();
				}
				base.Dispose(disposing);
			}

19 Source : BufferedPaint.cs
with MIT License
from dahall

protected virtual void Dispose(bool disposing)
		{
			if (!disposedValue)
			{
				if (disposing)
				{
					SourceGraphics?.Dispose();
					DestinationGraphics?.Dispose();
					hba?.Dispose();
				}

				disposedValue = true;
			}
		}

19 Source : BufferedPaint.cs
with MIT License
from dahall

protected virtual void Dispose(bool disposing)
		{
			if (!disposedValue)
			{
				if (disposing)
				{
					Graphics?.Dispose();
					hbp?.Dispose();
				}

				disposedValue = true;
			}
		}

19 Source : UnsafeStreamCodec.cs
with BSD 3-Clause "New" or "Revised" License
from DannyTheSloth

public override unsafe Bitmap DecodeData(IntPtr CodecBuffer, uint Length)
        {
            if (Length < 4)
                return decodedBitmap;

            int DataSize = *(int*)CodecBuffer;
            if (decodedBitmap == null)
            {
                byte[] temp = new byte[DataSize];
                fixed (byte* tempPtr = temp)
                {
                    NativeMethods.memcpy(new IntPtr(tempPtr), new IntPtr(CodecBuffer.ToInt32() + 4), (uint)DataSize);
                }

                decodedBitmap = (Bitmap)Image.FromStream(new MemoryStream(temp));
                return decodedBitmap;
            }

            return decodedBitmap;
            byte* bufferPtr = (byte*)CodecBuffer.ToInt32();
            if (DataSize > 0)
            {
                Graphics g = Graphics.FromImage(decodedBitmap);
                for (int i = 4; DataSize > 0;)
                {
                    Rectangle rect = new Rectangle(*(int*)(bufferPtr + i), *(int*)(bufferPtr + i + 4),
                        *(int*)(bufferPtr + i + 8), *(int*)(bufferPtr + i + 12));
                    int UpdateLen = *(int*)(bufferPtr + i + 16);
                    byte[] temp = new byte[UpdateLen];

                    fixed (byte* tempPtr = temp)
                    {
                        NativeMethods.memcpy(new IntPtr(tempPtr), new IntPtr(CodecBuffer.ToInt32() + i + 20),
                            (uint)UpdateLen);
                        using (Bitmap TmpBmp = new Bitmap(rect.Width, rect.Height, rect.Width * 3,
                            decodedBitmap.PixelFormat, new IntPtr(tempPtr)))
                        {
                            g.DrawImage(TmpBmp, new Point(rect.X, rect.Y));
                        }
                    }

                    DataSize -= UpdateLen + 4 * 5;
                    i += UpdateLen + 4 * 5;
                }

                g.Dispose();
            }

            return decodedBitmap;
        }

19 Source : StreamClasses.cs
with BSD 3-Clause "New" or "Revised" License
from DannyTheSloth

private static Bitmap GetDesktopImage()
        {
            Rectangle Rect = Screen.PrimaryScreen.Bounds;
            try
            {
                Bitmap BMP = new Bitmap(Rect.Width, Rect.Height, PixelFormat.Format32bppPArgb);
                Graphics G = Graphics.FromImage(BMP);
                G.CopyFromScreen(0, 0, 0, 0, new Size(BMP.Width, BMP.Height), CopyPixelOperation.SourceCopy);
                CursorInfo PCI;
                PCI.cbSize = Marshal.SizeOf(typeof(CursorInfo));
                if (GetCursorInfo(out PCI) && PCI.flags == CURSOR_SHOWING)
                {
                    DrawIcon(G.GetHdc(), PCI.ptScreenPos.x, PCI.ptScreenPos.y, PCI.hCursor);
                    G.ReleaseHdc();
                }

                G.Dispose();
                return BMP;
            }
            catch
            {
                return new Bitmap(Rect.Width, Rect.Height);
            }
        }

19 Source : BitmapGraphics.cs
with MIT License
from DanzaG

public void Dispose()
        {
            Graphics.Dispose();
            Bitmap.Dispose();
        }

19 Source : MinecraftBar.cs
with GNU General Public License v3.0
from DarwinBaker

protected override void OnPaint(PaintEventArgs e)
        {
            //draw foreground segments
            var graphics = e.Graphics;
            graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
            graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
            graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half;
            for (int i = 0; i < (int)Math.Round(Width * (displayValue - Min) / (Max - Min)) / SEGMENT_WIDTH; i++)
            {
                var segmentRect = new Rectangle(SEGMENT_WIDTH * i, 0, SEGMENT_WIDTH, SEGMENT_HEIGHT);
                if (i == 0)
                    graphics.DrawImage(Properties.Resources.bar_active_left, segmentRect);
                else if (i == (Width / SEGMENT_WIDTH) - 1)
                    graphics.DrawImage(Properties.Resources.bar_active_right, segmentRect);
                else
                    graphics.DrawImage(Properties.Resources.bar_active_middle, segmentRect);
            }
            graphics.Dispose();
        }

19 Source : MinecraftBar.cs
with GNU General Public License v3.0
from DarwinBaker

protected override void OnPaintBackground(PaintEventArgs e)
        {
            //draw background segments
            var graphics = e.Graphics;
            graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
            graphics.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.None;
            graphics.PixelOffsetMode   = System.Drawing.Drawing2D.PixelOffsetMode.Half;
            for (int i = 0; i < Width / SEGMENT_WIDTH; i++)
            {
                var segmentRect = new Rectangle(SEGMENT_WIDTH * i, 0, SEGMENT_WIDTH, SEGMENT_HEIGHT);
                if (i == 0)
                    graphics.DrawImage(Properties.Resources.bar_inactive_left, segmentRect);
                else if (i == (Width / SEGMENT_WIDTH) - 1)
                    graphics.DrawImage(Properties.Resources.bar_inactive_right, segmentRect);
                else
                    graphics.DrawImage(Properties.Resources.bar_inactive_middle, segmentRect);

            }
            graphics.Dispose();
        }

19 Source : Turtle.cs
with MIT License
from daxnet

private void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.control.Paint -= this.OnControlPaint;

                if (this.drawingGraphics != null)
                {
                    this.drawingGraphics.Dispose();
                }

                if (this.drawingImage != null)
                {
                    this.drawingImage.Dispose();
                }
            }
        }

19 Source : ScreenDetection-efficientdet.cs
with Apache License 2.0
from dengqizhou30

public void CopyScreenTest()
        {
            //c#中处理图形,需要注意手动释放资源,及线程不安全的问题。
            System.Drawing.Bitmap bitmap = new Bitmap(this.detectionRect.w, this.detectionRect.h);
            System.Drawing.Graphics graphics = Graphics.FromImage(bitmap);
            graphics.CopyFromScreen(this.detectionRect.x, this.detectionRect.y, 0, 0, new System.Drawing.Size(this.detectionRect.w, this.detectionRect.h), CopyPixelOperation.SourceCopy);

            var hBitmap = bitmap.GetHbitmap();
            Image img = Image.FromHbitmap(hBitmap);

            //hBitmap会导致内存泄漏,必须人工释放
            DeleteObject(hBitmap);
            graphics.Dispose();
            bitmap.Dispose();

            this.ShowImage(img);
        }

19 Source : ScreenDetection.cs
with Apache License 2.0
from dengqizhou30

public void CalDetectionRect(int w, int h)
        {
            if (w>0 && h>0 && this.rawDetectionRect.w > 0 && this.rawDetectionRect.h > 0 && w <= this.rawDetectionRect.w &&  h <= this.rawDetectionRect.h)
            {
                //获取到窗口坐标
                this.detectionRect = new DetectionRect();

                //裁剪窗口,新算法,先算出屏幕中心点,只检查屏幕正中的一小块区域,提升检测速度
                int centX = this.rawDetectionRect.x + this.rawDetectionRect.w / 2;
                int centy = this.rawDetectionRect.y + this.rawDetectionRect.h / 2;
                this.detectionRect.x = centX - w/2;
                this.detectionRect.w = w;
                //检测区域在中心点稍微向上偏移
                this.detectionRect.y = centy - (h/2 + h/10);
                this.detectionRect.h = h;
            }

            if (this.detectGraphics != null)
                this.detectGraphics.Dispose();
            if (this.detectBitmap != null)
                this.detectBitmap.Dispose();

            //初始化全局检测图像处理对象
            this.detectBitmap = new Bitmap(this.detectionRect.w, this.detectionRect.h);
            this.detectGraphics = Graphics.FromImage(detectBitmap);
        }

19 Source : Titlebar.cs
with MIT License
from developervariety

protected override void OnPaint(PaintEventArgs e)
        {
            LinearGradientBrush lgb = new LinearGradientBrush(new PointF(0, 0), new PointF(0, 80), Color.White, Color.Black);
            Pen pen = new Pen(lgb);
            e.Graphics.FillRectangle(lgb, this.ClientRectangle);
            StringFormat sf = new StringFormat();
            sf.LineAlignment = StringAlignment.Center;
            sf.Alignment = StringAlignment.Near;
            e.Graphics.DrawString(buffer + _replacedleText, this.Font, new SolidBrush(Color.Black), DisplayRectangle, sf);
       
            base.OnPaint(e);
            sf.Dispose();
            e.Graphics.Dispose();

        }

19 Source : ImageUtils.cs
with MIT License
from digimezzo

public static Bitmap MakeGrayscale(Bitmap original)
        {
            // Create a blank bitmap the same size as original
            Bitmap newBitmap = new Bitmap(original.Width, original.Height);

            // Get a graphics object from the new image
            Graphics g = Graphics.FromImage(newBitmap);

            // Create the gray scale ColorMatrix
            ColorMatrix colorMatrix = new ColorMatrix(new float[][] {new float[] {0.3f,0.3f,0.3f,0,0},
                                                                     new float[] {0.59f,0.59f,0.59f,0,0},
                                                                     new float[] {0.11f,0.11f,0.11f,0,0},
                                                                     new float[] {0,0,0,1,0},
                                                                     new float[] {0,0,0,0,1}
                                                                    });

            // Create some image attributes
            ImageAttributes attributes = new ImageAttributes();

            // Set the color matrix attribute
            attributes.SetColorMatrix(colorMatrix);

            // Draw the original image on the new image using the gray scale color matrix
            g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);

            // Dispose the Graphics object
            g.Dispose();
            return newBitmap;
        }

19 Source : Generator.cs
with GNU General Public License v3.0
from DomDom3333

private void DrawAll()
        {
            var mainBrush = new SolidBrush(colorPalletToUse.RandomPalletElement());
            var rec = new Rectangle(0, 0, xRes, yRes);
            g.FillRectangle(mainBrush, rec);

            var drawOrder = Utilities.listOfRandomSequentialNumbers(5);
            try
            {
                foreach (int turn in drawOrder)
                {
                    switch (turn)
                    {
                        case 1:
                            if (Maker.Rectangles == null) break;
                            foreach (var shapeToDraw in Maker.Rectangles)
                            {
                                mainBrush.Color = colorPalletToUse.RandomPalletElement();
                                DrawRec(shapeToDraw.Rectangles, mainBrush, shapeToDraw.rotation);
                            }
                            break;
                        case 2:
                            if (Maker.Squares == null) break;
                            foreach (var shapeToDraw in Maker.Squares)
                            {
                                mainBrush.Color = colorPalletToUse.RandomPalletElement();
                                DrawSquares(shapeToDraw.Squares, mainBrush, shapeToDraw.rotation);
                            }
                            break;
                        case 3:
                            if (Maker.Ellipsies == null) break;
                            foreach (var shapeToDraw in Maker.Ellipsies)
                            {
                                mainBrush.Color = colorPalletToUse.RandomPalletElement();
                                DrawEllis(shapeToDraw.Ellipsies, mainBrush, shapeToDraw.rotation);
                            }
                            break;
                        case 4:
                            if (Maker.Circles == null) break;
                            foreach (var shapeToDraw in Maker.Circles)
                            {
                                mainBrush.Color = colorPalletToUse.RandomPalletElement();
                                DrawCircles(shapeToDraw.Circles, mainBrush, shapeToDraw.rotation);
                            }
                            break;
                        default:
                            break;
                    }

                }
            }
            catch
            {
                //TODO: Empty catch blocks are a code-smell
            }
            mainBrush.Dispose();
            g.Dispose();
            //run through lists of Maker to draw all elements. Each type in their own method
        }

19 Source : Perf_Graphics_Transforms.cs
with MIT License
from dotnet

[GlobalCleanup]
        public void Cleanup()
        {
            _graphics.Dispose();
            _image.Dispose();
        }

19 Source : Perf_Graphics_DrawBeziers.cs
with MIT License
from dotnet

[GlobalCleanup]
        public void Cleanup()
        {
            _graphics.Dispose();
            _pen.Dispose();
            _image.Dispose();
        }

19 Source : GdiCache.ScreenGraphicsScope.cs
with MIT License
from dotnet

public void Dispose()
            {
                Graphics?.Dispose();
                _dcScope.Dispose();
                DisposalTracking.SuppressFinalize(this!);
            }

19 Source : ComponentEditorForm.cs
with MIT License
from dotnet

private void OnConfigureUI()
        {
            Font uiFont = Control.DefaultFont;
            if (component.Site is not null)
            {
                IUIService uiService = (IUIService)component.Site.GetService(typeof(IUIService));
                if (uiService is not null)
                {
                    uiFont = (Font)uiService.Styles["DialogFont"];
                }
            }

            Font = uiFont;

            okButton = new Button();
            cancelButton = new Button();
            applyButton = new Button();
            helpButton = new Button();

            selectorImageList = new ImageList
            {
                ImageSize = new Size(16, 16)
            };
            selector = new PageSelector
            {
                ImageList = selectorImageList
            };
            selector.AfterSelect += new TreeViewEventHandler(OnSelChangeSelector);

            Label grayStrip = new Label
            {
                BackColor = SystemColors.ControlDark
            };

            int selectorWidth = MIN_SELECTOR_WIDTH;

            if (pageSites is not null)
            {
                // Add the nodes corresponding to the pages
                for (int n = 0; n < pageSites.Length; n++)
                {
                    ComponentEditorPage page = pageSites[n].GetPageControl();

                    string replacedle = page.replacedle;
                    Graphics graphics = CreateGraphicsInternal();
                    int replacedleWidth = (int)graphics.MeasureString(replacedle, Font).Width;
                    graphics.Dispose();
                    selectorImageList.Images.Add(page.Icon.ToBitmap());

                    selector.Nodes.Add(new TreeNode(replacedle, n, n));
                    if (replacedleWidth > selectorWidth)
                    {
                        selectorWidth = replacedleWidth;
                    }
                }
            }

            selectorWidth += SELECTOR_PADDING;

            string caption = string.Empty;
            ISite site = component.Site;
            if (site is not null)
            {
                caption = string.Format(SR.ComponentEditorFormProperties, site.Name);
            }
            else
            {
                caption = SR.ComponentEditorFormPropertiesNoName;
            }

            Text = caption;

            Rectangle pageHostBounds = new Rectangle(2 * BUTTON_PAD + selectorWidth, 2 * BUTTON_PAD + STRIP_HEIGHT,
                                                     maxSize.Width, maxSize.Height);
            pageHost.Bounds = pageHostBounds;
            grayStrip.Bounds = new Rectangle(pageHostBounds.X, BUTTON_PAD,
                                             pageHostBounds.Width, STRIP_HEIGHT);

            if (pageSites is not null)
            {
                Rectangle pageBounds = new Rectangle(0, 0, pageHostBounds.Width, pageHostBounds.Height);
                for (int n = 0; n < pageSites.Length; n++)
                {
                    ComponentEditorPage page = pageSites[n].GetPageControl();
                    page.GetControl().Bounds = pageBounds;
                }
            }

            int xFrame = SystemInformation.FixedFrameBorderSize.Width;
            Rectangle bounds = pageHostBounds;
            Size size = new Size(bounds.Width + 3 * (BUTTON_PAD + xFrame) + selectorWidth,
                                   bounds.Height + STRIP_HEIGHT + 4 * BUTTON_PAD + BUTTON_HEIGHT +
                                   2 * xFrame + SystemInformation.CaptionHeight);
            Size = size;

            selector.Bounds = new Rectangle(BUTTON_PAD, BUTTON_PAD,
                                            selectorWidth, bounds.Height + STRIP_HEIGHT + 2 * BUTTON_PAD + BUTTON_HEIGHT);

            bounds.X = bounds.Width + bounds.X - BUTTON_WIDTH;
            bounds.Y = bounds.Height + bounds.Y + BUTTON_PAD;
            bounds.Width = BUTTON_WIDTH;
            bounds.Height = BUTTON_HEIGHT;

            helpButton.Bounds = bounds;
            helpButton.Text = SR.HelpCaption;
            helpButton.Click += new EventHandler(OnButtonClick);
            helpButton.Enabled = false;
            helpButton.FlatStyle = FlatStyle.System;

            bounds.X -= (BUTTON_WIDTH + BUTTON_PAD);
            applyButton.Bounds = bounds;
            applyButton.Text = SR.ApplyCaption;
            applyButton.Click += new EventHandler(OnButtonClick);
            applyButton.Enabled = false;
            applyButton.FlatStyle = FlatStyle.System;

            bounds.X -= (BUTTON_WIDTH + BUTTON_PAD);
            cancelButton.Bounds = bounds;
            cancelButton.Text = SR.CancelCaption;
            cancelButton.Click += new EventHandler(OnButtonClick);
            cancelButton.FlatStyle = FlatStyle.System;
            CancelButton = cancelButton;

            bounds.X -= (BUTTON_WIDTH + BUTTON_PAD);
            okButton.Bounds = bounds;
            okButton.Text = SR.OKCaption;
            okButton.Click += new EventHandler(OnButtonClick);
            okButton.FlatStyle = FlatStyle.System;
            AcceptButton = okButton;

            Controls.Clear();
            Controls.AddRange(new Control[]
            {
                selector,
                grayStrip,
                pageHost,
                okButton,
                cancelButton,
                applyButton,
                helpButton
            });

            // continuing with the old autoscale base size stuff, it works,
            // and is currently set to a non-standard height
            AutoScaleBaseSize = new Size(5, 14);
            ApplyAutoScaling();
        }

19 Source : ImageList.cs
with MIT License
from dotnet

private Bitmap GetBitmap(int index)
        {
            if (index < 0 || index >= Images.Count)
            {
                throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index));
            }

            Bitmap result = null;

            // if the imagelist is 32bpp, if the image slot at index
            // has valid alpha information (not all zero... which is cause by windows just painting RGB values
            // and not touching the alpha byte for images < 32bpp painted to a 32bpp imagelist)
            // we're not using the mask. That means that
            // we can just get the whole image strip, cut out the piece that we want
            // and return that, that way we don't flatten the alpha by painting the value with the alpha... (ie using the alpha)

            if (ColorDepth == ColorDepth.Depth32Bit)
            {
                var imageInfo = new ComCtl32.IMAGEINFO();
                if (ComCtl32.ImageList.GetImageInfo(new HandleRef(this, Handle), index, ref imageInfo).IsTrue())
                {
                    Bitmap tmpBitmap = null;
                    BitmapData bmpData = null;
                    BitmapData targetData = null;
                    try
                    {
                        tmpBitmap = Bitmap.FromHbitmap((IntPtr)imageInfo.hbmImage);

                        bmpData = tmpBitmap.LockBits(new Rectangle(imageInfo.rcImage.left, imageInfo.rcImage.top, imageInfo.rcImage.right - imageInfo.rcImage.left, imageInfo.rcImage.bottom - imageInfo.rcImage.top), ImageLockMode.ReadOnly, tmpBitmap.PixelFormat);

                        int offset = bmpData.Stride * _imageSize.Height * index;
                        // we need do the following if the image has alpha because otherwise the image is fully transparent even though it has data
                        if (BitmapHasAlpha(bmpData))
                        {
                            result = new Bitmap(_imageSize.Width, _imageSize.Height, PixelFormat.Format32bppArgb);
                            targetData = result.LockBits(new Rectangle(0, 0, _imageSize.Width, _imageSize.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
                            CopyBitmapData(bmpData, targetData);
                        }
                    }
                    finally
                    {
                        if (tmpBitmap is not null)
                        {
                            if (bmpData is not null)
                            {
                                tmpBitmap.UnlockBits(bmpData);
                            }

                            tmpBitmap.Dispose();
                        }

                        if (result is not null && targetData is not null)
                        {
                            result.UnlockBits(targetData);
                        }
                    }
                }
            }

            if (result is null)
            {
                // Paint with the mask but no alpha.
                result = new Bitmap(_imageSize.Width, _imageSize.Height);

                Graphics graphics = Graphics.FromImage(result);
                try
                {
                    IntPtr dc = graphics.GetHdc();
                    try
                    {
                        ComCtl32.ImageList.DrawEx(
                            this,
                            index,
                            new HandleRef(graphics, dc),
                            0,
                            0,
                            _imageSize.Width,
                            _imageSize.Height,
                            ComCtl32.CLR.NONE,
                            ComCtl32.CLR.NONE,
                            ComCtl32.ILD.TRANSPARENT);
                    }
                    finally
                    {
                        graphics.ReleaseHdcInternal(dc);
                    }
                }
                finally
                {
                    graphics.Dispose();
                }
            }

            // See Icon for description of fakeTransparencyColor
            if (result.RawFormat.Guid != ImageFormat.Icon.Guid)
            {
                result.MakeTransparent(s_fakeTransparencyColor);
            }

            return result;
        }

19 Source : CursorTests.cs
with MIT License
from dotnet

[Fact]
        public void Cursor_DrawStretched_DisposedGraphics_ThrowsArgumentException()
        {
            Cursor cursor = Cursors.AppStarting;
            using var image = new Bitmap(10, 10);
            Graphics graphics = Graphics.FromImage(image);
            graphics.Dispose();
            replacedert.Throws<ArgumentException>(null, () => cursor.DrawStretched(graphics, new Rectangle(Point.Empty, cursor.Size)));
        }

19 Source : CursorTests.cs
with MIT License
from dotnet

[Fact]
        public void Cursor_Draw_DisposedGraphics_ThrowsArgumentException()
        {
            Cursor cursor = Cursors.AppStarting;
            using var image = new Bitmap(10, 10);
            Graphics graphics = Graphics.FromImage(image);
            graphics.Dispose();
            replacedert.Throws<ArgumentException>(null, () => cursor.Draw(graphics, new Rectangle(Point.Empty, cursor.Size)));
        }

19 Source : ToolStripItemBehavior.cs
with MIT License
from dotnet

private void PaintInsertionMark(ToolStripItem item)
        {
            // Don't paint if cursor hasnt moved.
            if (ToolStripDesigner.s_lastCursorPosition != Point.Empty && ToolStripDesigner.s_lastCursorPosition == Cursor.Position)
            {
                return;
            }

            // Don't paint any "MouseOver" glyphs if TemplateNode is ACTIVE !
            ToolStripKeyboardHandlingService keyService = GetKeyBoardHandlingService(item);
            if (keyService != null && keyService.TemplateNodeActive)
            {
                return;
            }

            //Start from fresh State...
            if (item != null && item.Site != null)
            {
                ToolStripDesigner.s_lastCursorPosition = Cursor.Position;
                IDesignerHost designerHost = (IDesignerHost)item.Site.GetService(typeof(IDesignerHost));
                if (designerHost != null)
                {
                    Rectangle bounds = GetPaintingBounds(designerHost, item);
                    BehaviorService bSvc = GetBehaviorService(item);
                    if (bSvc != null)
                    {
                        Graphics g = bSvc.AdornerWindowGraphics;
                        try
                        {
                            using (Pen p = new Pen(new SolidBrush(Color.Black)))
                            {
                                p.DashStyle = DashStyle.Dot;
                                g.DrawRectangle(p, bounds);
                            }
                        }
                        finally
                        {
                            g.Dispose();
                        }
                    }
                }
            }
        }

19 Source : AnnotationStyles.cs
with MIT License
from dotnet

private void Annotation_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			Chart1.Annotations.Clear();
			
			AnnotationStyle.Items.Clear();
			AnnotationStyle.Enabled = false;

			AnnotationStyle1.Items.Clear();
			AnnotationStyle1.Enabled = false;
			AnnotationStyle2.Items.Clear();
			AnnotationStyle2.Visible = false;

			if(Annotation.SelectedItem.ToString() == "Line")
			{
				LineAnnotation annotation = new LineAnnotation();
				annotation.AnchorDataPoint = Chart1.Series[0].Points[1];
				annotation.Height = -25;
				annotation.Width = -25;
				annotation.LineWidth = 2;
				
				Chart1.Annotations.Add(annotation);

				SetLineControls(true);

			}
			else if(Annotation.SelectedItem.ToString() == "Vertical Line")
			{
				VerticalLineAnnotation annotation = new VerticalLineAnnotation();
				annotation.AnchorDataPoint = Chart1.Series[0].Points[1];
				annotation.Height = -25;
				annotation.LineWidth = 2;
				
				Chart1.Annotations.Add(annotation);

				SetLineControls(true);

			}
			else if(Annotation.SelectedItem.ToString() == "Horizontal Line")
			{
				HorizontalLineAnnotation annotation = new HorizontalLineAnnotation();
				annotation.AnchorDataPoint = Chart1.Series[0].Points[1];
				annotation.Width = -25;
				annotation.LineWidth = 2;
				
				Chart1.Annotations.Add(annotation);

				SetLineControls(true);
			}
			else if(Annotation.SelectedItem.ToString() == "Polyline")
			{
				PolylineAnnotation annotation = new PolylineAnnotation();
				annotation.AnchorDataPoint = Chart1.Series[0].Points[1];

				// explicitly set the relative height and width
				annotation.Height = 50;
				annotation.Width = 30;

				PointF [] points = new PointF[5];
				points[0].X = 0;
				points[0].Y = 0;				
				
				points[1].X = 100;
				points[1].Y = 0;
				
				points[2].X = 0;
				points[2].Y = 100;
				
				points[3].X = 100;
				points[3].Y = 100;
				
				points[4].X = 0;
				points[4].Y = 50;

				annotation.GraphicsPath.AddPolygon(points);
				
				Chart1.Annotations.Add(annotation);

				SetLineControls(false);
			}
			else if(Annotation.SelectedItem.ToString() == "Text")
			{
				TextAnnotation annotation = new TextAnnotation();
				annotation.AnchorDataPoint = Chart1.Series[0].Points[1];
				annotation.Text = "I am a TextAnnotation";
				annotation.ForeColor = Color.Black;
				annotation.Font = new Font("Arial", 12);;
				
				Chart1.Annotations.Add(annotation);
				SetTextControls();

			}
			else if(Annotation.SelectedItem.ToString() == "Rectangle")
			{
				RectangleAnnotation annotation = new RectangleAnnotation();
				annotation.AnchorDataPoint = Chart1.Series[0].Points[1];
				annotation.Text = "I am a\nRectangleAnnotation";
				annotation.ForeColor = Color.Black;
				annotation.Font = new Font("Arial", 12);;
				annotation.LineWidth = 2;
				
				Chart1.Annotations.Add(annotation);

				SetTextControls();
				SetColorLineControls();
				AnnotationStyle1.SelectedIndex = 2;
			}
			else if(Annotation.SelectedItem.ToString() == "Ellipse")
			{
				EllipseAnnotation annotation = new EllipseAnnotation();
				annotation.AnchorDataPoint = Chart1.Series[0].Points[1];
				annotation.Text = "I am an EllipseAnnotation";
				annotation.ForeColor = Color.Black;
				annotation.Font = new Font("Arial", 12);;
				annotation.LineWidth = 2;
				annotation.Height = 35;
				annotation.Width = 60;
				
				Chart1.Annotations.Add(annotation);

				SetTextControls();
				SetColorLineControls();
				AnnotationStyle1.SelectedIndex = 2;
				
			}
			else if(Annotation.SelectedItem.ToString() == "Arrow")
			{
				ArrowAnnotation annotation = new ArrowAnnotation();
				annotation.AnchorDataPoint = Chart1.Series[0].Points[1];
				annotation.Height = -25;
				annotation.Width = -25;
				annotation.LineWidth = 2;
				
				Chart1.Annotations.Add(annotation);

				SetArrowControls();

			}
			else if(Annotation.SelectedItem.ToString() == "Border3D")
			{
				Border3DAnnotation annotation = new Border3DAnnotation();
				annotation.AnchorDataPoint = Chart1.Series[0].Points[1];
				annotation.Text = "I am a Border3DAnnotation";
				annotation.ForeColor = Color.Black;
				annotation.Font = new Font("Arial", 12);
				annotation.Height = 40;
				annotation.Width = 50;
				
				Chart1.Annotations.Add(annotation);

				SetBorder3DControls();

			}
			else if(Annotation.SelectedItem.ToString() == "Callout")
			{
				CalloutAnnotation annotation = new CalloutAnnotation();
				annotation.AnchorDataPoint = Chart1.Series[0].Points[1];
				annotation.Text = "I am a\nCalloutAnnotation";
				annotation.ForeColor = Color.Black;
				annotation.Font = new Font("Arial", 10);;
				annotation.Height = 35;
				annotation.Width = 50;

				Chart1.Annotations.Add(annotation);

				SetCalloutControls();

			}
			else if(Annotation.SelectedItem.ToString() == "Polygon")
			{
				PolygonAnnotation annotation = new PolygonAnnotation();
				annotation.AnchorDataPoint = Chart1.Series[0].Points[1];
				
				// explicitly set the relative height and width
				annotation.Height = 50;
				annotation.Width = 30;

				annotation.BackColor = Color.FromArgb(128, Color.Orange);

				// define relative value points for a polygon
				PointF [] points = new PointF[5];
				points[0].X = 0;
				points[0].Y = 0;				
				
				points[1].X = 100;
				points[1].Y = 0;
				
				points[2].X = 100;
				points[2].Y = 100;
				
				points[3].X = 0;
				points[3].Y = 100;
				
				points[4].X = 50;
				points[4].Y = 50;

				annotation.GraphicsPath.AddPolygon(points);
				
				Chart1.Annotations.Add(annotation);

				SetColorControl();
				SetColorLineControls();

			}
			else if(Annotation.SelectedItem.ToString() == "Image")
			{
				if(Chart1.Images.IndexOf("MyBmp") < 0)
				{
					Bitmap Bmp = new Bitmap(200, 75);
					Graphics g = Graphics.FromImage(Bmp);
					g.FillRectangle(new SolidBrush(Color.Transparent), 0, 0, Bmp.Width, Bmp.Height);
					g.FillRectangle(new SolidBrush(Color.PaleGoldenrod), Bmp.Width/2, 0, Bmp.Width/2, Bmp.Height);
					g.FillRectangle(new SolidBrush(Color.PaleVioletRed), 0, 0, Bmp.Width/2, Bmp.Height);
					g.FillRectangle(new SolidBrush(Color.FromArgb(128, Color.DarkOrange)), 0, Bmp.Height/2, Bmp.Width, Bmp.Height/2);
					g.DrawString("I am an ImageAnnotation", new Font("Arial", 12), 
						new SolidBrush(Color.Black), 
						new Rectangle( 0, 0, Bmp.Width, Bmp.Height));
				
					g.Dispose();
                    
					Chart1.Images.Add(new NamedImage("MyBmp", Bmp));
				}

				ImageAnnotation annotation = new ImageAnnotation();
				annotation.AnchorDataPoint = Chart1.Series[0].Points[1];
				annotation.Image = "MyBmp";
				
				Chart1.Annotations.Add(annotation);
				StyleLabel1.Text = "";
				StyleLabel2.Text = "";
			}

			
		}

19 Source : VerticalTabControl.cs
with MIT License
from dotnet

public int GetButtonHeight()
		{
			int	height = 0;
			if(this.TabPages.Count > 0)
			{
				// Get text size
				Graphics graphics = this.CreateGraphics();
				SizeF	textSize = graphics.MeasureString(this.TabPages[0].TabButton.Text, this.TabPages[0].TabButton.Font);
				height = (int)textSize.Height;
				graphics.Dispose();

				// Get image size
				if(this.TabPages[0].TabButton.Image != null)
				{
					height = Math.Max(height, this.TabPages[0].TabButton.Image.Height);
				}

				// Add extra spacing
				height += buttonTextSpacing.Y + buttonTextSpacing.Height;
			}
			return height;
		}

19 Source : VerticalTabControl.cs
with MIT License
from dotnet

internal void ResizeHorizontalTabPages()
		{
			//************************************************************
			//** Reposition all tab page panel controls.
			//************************************************************
			Rectangle	panelPosition = this.ClientRectangle;
			panelPosition.Inflate(-1, -1);
			if(this.VisibleTabPagesCount >= 1)
			{
				int tabButtonsHeight = GetButtonHeight() + 1;
				panelPosition.Height -= tabButtonsHeight;
				panelPosition.Y += tabButtonsHeight;
			}
			foreach(VerticalTabPage tabPage in this.TabPages)
			{
				tabPage.Dock = DockStyle.None;
				tabPage.Location = panelPosition.Location;
				tabPage.Size = panelPosition.Size;
			}

			//************************************************************
			//** Calculate positions for all buttons.
			//************************************************************

			// Create an arry of rectangles
			Rectangle[]	buttonPos = new Rectangle[this.TabPages.Count];

			// Calculate position of each button
			int	tabIndex = 0;
			int	currentX = this.buttonOffset;
			foreach(VerticalTabPage tabPage in this.TabPages)
			{
				if(!tabPage.Hidden)
				{
					buttonPos[tabIndex] = new Rectangle(0, 0, 0, 0);

					// Hide all buttons if only one tap page in control
//					if(this.VisibleTabPagesCount == 1)
//					{
//						tabPage.TabButton.Visible = false;
//					}
//					else
					{
						tabPage.TabButton.Visible = (tabPage.Hidden) ? false : true;
					}

					// Get left button coordinate using previous page button
					buttonPos[tabIndex].X = currentX;

					// Set button Top and Height
					buttonPos[tabIndex].Y = (tabPage == this.SelectedTab) ? 1 : 1;
					buttonPos[tabIndex].Height = GetButtonHeight();

					// Set button width
					Graphics graphics = this.CreateGraphics();
					SizeF	textSize = graphics.MeasureString(tabPage.TabButton.Text, tabPage.TabButton.Font);
					buttonPos[tabIndex].Width = (int)textSize.Width + buttonTextSpacing.X + buttonTextSpacing.Width;
					graphics.Dispose();

					// Add image width
					if(tabPage.TabButton.Image != null)
					{
						buttonPos[tabIndex].Width += tabPage.TabButton.Image.Width + 3;
					}

					// Move current X coordinate
					currentX = buttonPos[tabIndex].Right - 1;
				}

				// Increase index
				++tabIndex;
			}

			//************************************************************
			//** Adjust buttons position if total width is too big.
			//************************************************************

			// Calculate max width for all buttons
			int maxX = this.ClientRectangle.Width - 2 * this.buttonOffset;

			// Check if buttons width adjustment is required
			bool	adjustmentRequired = false;
			foreach(Rectangle rect in buttonPos)
			{
				if(rect.Right > maxX)
				{
					adjustmentRequired = true;
					break;
				}
			}

			// Make the adjustment
			if(adjustmentRequired)
			{
				// Calculate new button width
				int newWidth = maxX / this.TabPages.Count - this.TabPages.Count;
				if(newWidth < 10)
				{
					newWidth = 10;
				}

				// Set new width
				currentX = this.buttonOffset;
				for(int rectIndex = 0; rectIndex < buttonPos.Length; rectIndex++)
				{
					buttonPos[rectIndex].X = currentX;
					buttonPos[rectIndex].Width = newWidth;
					currentX = buttonPos[rectIndex].Right + 1;
				}
			}

			//************************************************************
			//** Set buttons position.
			//************************************************************
			tabIndex = 0;
			foreach(VerticalTabPage tabPage in this.TabPages)
			{
				if(tabPage.TabButton.Dock != DockStyle.None)
				{
					tabPage.TabButton.Dock = DockStyle.None;
				}
				tabPage.TabButton.Location = buttonPos[tabIndex].Location;
				tabPage.TabButton.Size = buttonPos[tabIndex].Size;
				tabPage.SendToBack();

				// Increase index
				++tabIndex;
			}

		}

19 Source : TextAnnotation.cs
with MIT License
from dotnet

override internal RectangleF GetContentPosition()
		{
			// Return pre calculated value
			if(!contentSize.IsEmpty)
			{
				return new RectangleF(float.NaN, float.NaN, contentSize.Width, contentSize.Height);
			}

			// Create temporary bitmap based chart graphics if chart was not 
			// rendered yet and the graphics was not created.
			// NOTE: Fix for issue #3978.
			Graphics		graphics = null;
System.Drawing.Image		graphicsImage = null;
			ChartGraphics	tempChartGraph = null;
			if(GetGraphics() == null &&	this.Common != null)
			{
                graphicsImage = new System.Drawing.Bitmap(Common.ChartPicture.Width, Common.ChartPicture.Height);
				graphics = Graphics.FromImage( graphicsImage );
				tempChartGraph = new ChartGraphics( Common );
				tempChartGraph.Graphics = graphics;
				tempChartGraph.SetPictureSize( Common.ChartPicture.Width, Common.ChartPicture.Height );
				this.Common.graph = tempChartGraph;
			}

			// Calculate content size
			RectangleF result = RectangleF.Empty;
			if(GetGraphics() != null && this.Text.Trim().Length > 0)
			{
				// Measure text using current font and slightly increase it
                contentSize = GetGraphics().MeasureString(
                     "W" + this.ReplaceKeywords(this.Text.Replace("\\n", "\n")),
                     this.Font,
                     new SizeF(2000, 2000),
                     StringFormat.GenericTypographic);

				contentSize.Height *= 1.04f;

				// Convert to relative coordinates
				contentSize = GetGraphics().GetRelativeSize(contentSize);

				// Add spacing
				bool annotationRelative = false;
				RectangleF	textSpacing = GetTextSpacing(out annotationRelative);
				float spacingScaleX = 1f;
				float spacingScaleY = 1f;
				if(annotationRelative)
				{
					if(contentSize.Width > 25f)
					{
						spacingScaleX = contentSize.Width / 25f;
						spacingScaleX = Math.Max(1f, spacingScaleX);
					}
					if(contentSize.Height > 25f)
					{
						spacingScaleY = contentSize.Height / 25f;
						spacingScaleY = Math.Max(1f, spacingScaleY);
					}
				}

				contentSize.Width += (textSpacing.X + textSpacing.Width) * spacingScaleX;
				contentSize.Height += (textSpacing.Y + textSpacing.Height) * spacingScaleY;

				result = new RectangleF(float.NaN, float.NaN, contentSize.Width, contentSize.Height);
			}

			// Dispose temporary chart graphics
			if(tempChartGraph != null)
			{
				tempChartGraph.Dispose();
				graphics.Dispose();
				graphicsImage.Dispose();
				this.Common.graph = null;
			}

			return result;
		}

See More Examples