c# drawing中如何绘制基本图形

655Z技术栈 C#编程 2025年07月07日 8

在C#中,你可以使用Windows Forms或WPF来绘制基本图形

  1. 首先,确保你已经添加了System.DrawingSystem.Windows.Forms引用。

  2. 创建一个新的Windows Forms应用程序项目。

  3. 在主窗体(Form1)上添加一个Paint事件处理程序。这可以通过双击窗体或在属性窗口中找到“Paint”事件并双击它来完成。

  4. 在Paint事件处理程序中,你可以使用Graphics对象来绘制基本图形。例如,以下代码绘制一个矩形:

private void Form1_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; Pen pen = new Pen(Color.Black, 2); Rectangle rect = new Rectangle(50, 50, 100, 100); g.DrawRectangle(pen, rect); }
  1. 若要绘制其他基本图形,如椭圆、线条等,请使用相应的Graphics方法,如DrawEllipseDrawLine等。例如,以下代码绘制一个椭圆和一条线:
private void Form1_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; Pen pen = new Pen(Color.Black, 2); // 绘制椭圆 Rectangle ellipseRect = new Rectangle(50, 50, 100, 50); g.DrawEllipse(pen, ellipseRect); // 绘制线条 Point point1 = new Point(200, 50); Point point2 = new Point(300, 150); g.DrawLine(pen, point1, point2); }
  1. 若要更改颜色或笔触宽度,只需修改Pen对象的属性。例如:
Pen pen = new Pen(Color.Red, 5);
  1. 若要填充图形,请使用Brush对象并调用相应的Fill方法,如FillRectangleFillEllipse等。例如,以下代码绘制一个填充的矩形:
private void Form1_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; Brush brush = new SolidBrush(Color.Blue); Rectangle rect = new Rectangle(50, 50, 100, 100); g.FillRectangle(brush, rect); }
  1. 若要绘制文本,请使用GraphicsDrawString方法。例如:
private void Form1_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; Font font = new Font("Arial", 12); Brush brush = new SolidBrush(Color.Black); PointF position = new PointF(50, 50); g.DrawString("Hello, World!", font, brush, position); }

这些示例仅展示了C#绘图的基本功能。你可以根据需要绘制更复杂的图形,并使用不同的颜色、笔触样式和填充效果。

提供PHP及ThinkPHP框架的定制开发、代码优化,PHP修改、ThinkPHP修改。

邮箱:yvsm@163.com 微信:yvsm316 QQ:316430983
关闭

用微信“扫一扫”