单击按钮绘制形状

本文关键字:绘制 按钮 单击 | 更新日期: 2023-09-27 18:20:19

我创建了一个Windows窗体应用程序,并希望在单击按钮时绘制一个形状。如何在Button_Click事件上调用Form_Paint?

单击按钮绘制形状

这里有一个快速示例,它将每个"形状"存储为类级别列表中的GraphicsPath。每个路径都是使用表单的Paint()事件中提供的Graphics绘制的。一个随机矩形被添加到List<>单击每个按钮,就会对窗体调用Refresh(),迫使它重新绘制自己:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.Paint += new PaintEventHandler(Form1_Paint);
    }
    private Random R = new Random();
    private List<System.Drawing.Drawing2D.GraphicsPath> Paths = new List<System.Drawing.Drawing2D.GraphicsPath>();
    private void button1_Click(object sender, EventArgs e)
    {
        Point pt1 = new Point(R.Next(this.Width), R.Next(this.Height));
        Point pt2 = new Point(R.Next(this.Width), R.Next(this.Height));
        System.Drawing.Drawing2D.GraphicsPath shape = new System.Drawing.Drawing2D.GraphicsPath();
        shape.AddRectangle(new Rectangle(new Point(Math.Min(pt1.X,pt2.X), Math.Min(pt1.Y, pt2.Y)), new Size(Math.Abs(pt2.X - pt1.X), Math.Abs(pt2.Y - pt1.Y))));
        Paths.Add(shape);
        this.Refresh();
    }
    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        Graphics G = e.Graphics;
        foreach (System.Drawing.Drawing2D.GraphicsPath Path in Paths)
        {
            G.DrawPath(Pens.Black, Path);
        }
    }
}

要手动提升Paint,请阅读此SO帖子(基本上称为Invalidate()方法)

SO post:我该如何称呼绘画事件?

然而,您可能需要在您的paint-even处理程序方法中设置/清除某种内部"drawshape"标志,单击并检查按钮。此标志将通知绘制事件处理程序继续绘制形状或根本不绘制形状(每次调用表单绘制时)