WinForms 应用程序中的控件是基于窗体的,当控件需要重绘时,它会向父窗体发送一个消息请求重绘。但是,控件本身并不直接处理绘制命令,所以你不能直接在控件上绘制图形。
解决方法:
- 重写控件的OnPaint方法
- 使用CreateGraphics方法
绘制直线:
//绘制线条,线条为虚线,虚线之间的间隔为3像素
Pen pen = new Pen(new SolidBrush(Color.Blue), 2);
pen.DashStyle = DashStyle.Solid;
e.Graphics.DrawLine(pen, 35, 24, 100, 60);
绘制椭圆,圆形:
//绘制椭圆,设置椭圆的大小和位置
Rectangle rect = new Rectangle(50, 50, 120, 100);
// 绘制椭圆边框
e.Graphics.DrawEllipse(Pens.Green, rect);
绘制扇形并填充:
//填充扇形
// 设置弧线的起点和终点
int x = 50;
int y = 50;
int width = 100;
int height = 50;
// 设置弧线的起始角度和角度范围(顺时针方向)
int startAngle = 0;
int sweepAngle = 90;
e.Graphics.FillPie(Brushes.LightBlue, x, y, width, height, startAngle, sweepAngle);
绘制弧线:
// 绘制弧线
// 设置弧线的起点和终点
int x1 = 100;
int y1 = 100;
int width1 = 80;
int height1 = 100;
// 设置弧线的起始角度和角度范围(顺时针方向)
float startAngle1 = -180;
float sweepAngle1 = 90;
e.Graphics.DrawArc(Pens.Black, x1, y1, width1, height1, startAngle1, sweepAngle1);
绘制多边形:
//绘制多边形
Color color = System.Drawing.Color.Red;
Brush brushes = new SolidBrush(color);
Point[] point = new Point[3];
point[0] = new Point(10, 10);
point[1] = new Point(40, 20);
point[2] = new Point(34, 30);
e.Graphics.FillPolygon(brushes, point);
实例代码:
https://download.csdn.net/download/lvxingzhe3/89420813
参考:
C# Winform GDI+ 绘图_c# 画图-CSDN博客