GDI繪圖常用的方法
阿新 • • 發佈:2018-12-17
1.畫矩形
Rectangle textCellBounds = new Rectangle(X,Y,Width,Height);
graphics.DrawRectangle(new Pen(ColorTranslator.FromHtml("#D7D7D7")), textCellBounds);
2.填充矩形
LinearGradientBrush backBrush = new LinearGradientBrush( this.Bounds, SystemColors.ControlLightLight, SystemColors.ControlLight, LinearGradientMode.Vertical); Rectangle textCellBounds = new Rectangle(X,Y,Width,Height); pevent.Graphics.FillRectangle(backBrush, this.Bounds);
3.畫/填充橢圓(圓形)
以矩形為框,獲得內接橢圓
System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath(); Rectangle textCellBounds = new Rectangle(X,Y,Width,Height); path.AddEllipse(textCellBounds); Brush fillBrush = new SolidBrush(GetRandomColor()); //畫橢圓 : DrawPath(Pen pen, GraphicsPath path); graphics.FillPath(fillBrush, path);//填充橢圓
4.畫/填充路徑
graphics.DrawPath(Pen pen, GraphicsPath path);//劃線
graphics.FillPath(fillBrush, path);//填充
5.加線
path.AddLine(left, top, left, top);
path.AddLine(left, top, right, top);
path.AddLine(right, top, right, botton);
path.AddLine(right, botton, left, botton);
6.畫弧
GraphicsPath graphicsPath = new GraphicsPath(); graphicsPath.AddArc(x, y, width, height, 180, 90);
6.幾個點連線
Graphics類
public void FillPolygon (System.Drawing.Brush brush, System.Drawing.Point[] points);
7.寫文字
方法一
//提供的快捷方式,類似的還有CheckBoxRenderer.DrawCheckBox 繪製checkBox
TextRenderer.DrawText
方法二
Graphics.DrawString
8.圖片的縮放與裁剪(裁剪成圓)
private Image CutEllipse(Image img, Size size)
{
try
{
Bitmap bitmap = new Bitmap(size.Width, size.Height);
using (Graphics graphics = Graphics.FromImage(bitmap))
{
using (TextureBrush brush = new TextureBrush(img, WrapMode.Tile))
{
brush.ScaleTransform((float)size.Width / img.Width, (float)size.Height / img.Height);
InitGraphics(graphics, true);
graphics.FillEllipse(brush, new Rectangle(Point.Empty, size));
}
}
return bitmap;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.StackTrace);//TODO:v6.0 zkk 考慮寫入日誌
return null;
}
}
9.矩形放大
Rectangle textCellBounds = new Rectangle(X,Y,Width,Height);
textCellBounds.Inflate(X,Y);
10. 抗鋸齒
private void InitGraphics(Graphics graphics, bool needOffsets = false)
{
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.PixelOffsetMode = needOffsets ? PixelOffsetMode.Half : PixelOffsetMode.HighQuality;
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
}