在按钮单击上绘制形状

时间:2013-06-29 19:24:38

标签: c# gdi+

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

2 个答案:

答案 0 :(得分:0)

这是一个快速示例,它将每个“形状”存储为类级别列表中的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);
        }
    }

}

答案 1 :(得分:0)

即使手动提高Paint,也请阅读此SO帖子(基本上调用Invalidate()方法)

SO post: How do I call paint event?

但是,您可能需要在按钮单击上设置/清除某种内部“drawshape”标志,并检查您的paint甚至处理程序方法。此标志将触发您的绘图事件处理程序,以继续绘制您的形状或根本不绘制您的形状(每次调用表单绘制时)