C# winform GDI 绘图–矩形,圆,多边形,直线虚线,文字,图形填充,饼状图等
代码如下:
private void Drawing_Paint(object sender, PaintEventArgs e)
{
Graphics g1 = e.Graphics;
//使绘图质量最高,即消除锯齿
g1.SmoothingMode = SmoothingMode.AntiAlias;
g1.InterpolationMode = InterpolationMode.HighQualityBicubic;
g1.CompositingQuality = CompositingQuality.HighQuality;
Pen p = new Pen(Color.Blue, 2);//定义笔的颜色为蓝色,大小为2
Brush fillBrush = new SolidBrush(Color.Red);
//画直线
g1.DrawLine(p, 200, 10, 300, 10);//在画板上画直线,起始坐标为(10,10),终点坐标为(100,100)
//画虚线
Pen px = new Pen(Color.Blue, 2);//定义笔的颜色为蓝色,大小为2
px.DashStyle = DashStyle.Dot;//定义虚线的样式为点
g1.DrawLine(px, 200, 20, 300, 20);
//自定义虚线
Pen pd = new Pen(Color.Black, 5);//定义笔的颜色为蓝色,大小为2
pd.DashPattern = new float[] { 2, 1 };//设置短划线和空白部分的数组
g1.DrawLine(pd, 200, 30, 300, 30);
//画箭头,只对不封闭曲线有用
pd.DashStyle = DashStyle.Solid;//恢复实线
pd.EndCap = LineCap.ArrowAnchor;//定义线尾的样式为箭头
g1.DrawLine(pd, 200, 50, 300, 50);
//画圆
g1.DrawEllipse(p, 200, 80, 280, 280);//与椭圆相贴的矩形的坐标,椭圆的长轴,椭圆的短轴
//单色填充圆
g1.FillEllipse(fillBrush, 200, 80, 280, 280);
//画矩形
Pen p2 = new Pen(Color.Yellow, 4);
g1.DrawRectangle(p2, 0, 310, 100, 100);
//用渐变色填充
Rectangle rect = new Rectangle(300, 60, 50, 50);//定义矩形,参数为起点横纵坐标以及其长和宽
rect.Location = new Point(330, 20);
LinearGradientBrush b3 = new LinearGradientBrush(rect, Color.Yellow, Color.Black, LinearGradientMode.Horizontal);
g1.FillRectangle(b3, rect);
//用图片填充
//TextureBrush b2 = new TextureBrush(Image.FromFile(@"e:\picture\1.jpg"));
//rect.Location = new Point(10, 70);//更改这个矩形的起点坐标
//rect.Width = 200;//更改这个矩形的宽来
//rect.Height = 200;//更改这个矩形的高
//g1.FillRectangle(b2, rect);
//绘制字符串
g1.DrawString("绘制文字", new Font("微软雅黑", 10), fillBrush, new PointF(130, 10));
//画多边形
Point[] pg = { new Point(0, 76),
new Point(80, 76),
new Point(106, 0),
new Point(130, 76),
new Point(210, 76),
new Point(146, 124),
new Point(170, 200),
new Point(106, 152),
new Point(40, 200),
new Point(66, 124),
};
g1.DrawPolygon(p, pg);
//画三维饼状图
int width = 200;
int height = 100;
int x = 440;
int y = 20;
Rectangle r = new Rectangle(x, y, width, height);
Pen p3 = new Pen(Color.Gray);
for (int i = y; i < 3 * y; i++)
{
Rectangle tempR = new Rectangle(x, i, width, height);
g1.DrawEllipse(p3, tempR);
}
Brush b = new SolidBrush(Color.Gainsboro);
g1.FillPie(b, r, 0, 360);//笔刷,基础矩形,扫过的角
b = new SolidBrush(Color.Blue);
g1.FillPie(b, r, 60, 150);
b = new SolidBrush(Color.Yellow);
g1.FillPie(b, r, 210, 150);//从210°开始掠过150度
Bitmap image = new Bitmap(500, 500);
Graphics g = Graphics.FromImage(image);
g.DrawEllipse(p, 200, 90, 100, 100);//与椭圆相贴的矩形的坐标,椭圆的长轴,椭圆的短轴
//单色填充圆
g.FillEllipse(fillBrush, 200, 90, 100, 100);
image.Save(@"c:\1.jpg");
#region 显示
//pictureBox1.Image = (Image)image;
//pictureBox1.Image.Save(@"c:\1.jpg");
//pictureBox1.Show();
#endregion
g1.Dispose();//释放由Graphics使用的资源
p.Dispose();
}