通过单击WinForms中的按钮在面板上绘图

时间:2016-02-05 08:46:38

标签: c# winforms visual-studio

我正在尝试通过点击按钮制作一个程序来绘制Panel(方形,圆形等等)。

到目前为止我没有做太多,只是直接尝试将代码绘制到面板但不知道如何将其移动到按钮。这是我到目前为止的代码。

如果你知道一种比我正在使用的方法更好的绘画方法,请告诉我。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void mainPanel_Paint(object sender, PaintEventArgs e)
    {
        Graphics g;
        g = CreateGraphics();
        Pen pen = new Pen(Color.Black);
        Rectangle r = new Rectangle(10, 10, 100, 100);
        g.DrawRectangle(pen, r);
    }

    private void circleButton_Click(object sender, EventArgs e)
    {
    }

    private void drawButton_Click(object sender, EventArgs e)
    {
    }
}

}

1 个答案:

答案 0 :(得分:2)

使用这个极其简化的示例类..:

class DrawAction
{
    public char type { get; set; }
    public Rectangle rect { get; set; }
    public Color color { get; set; }
    //.....

    public DrawAction(char type_, Rectangle rect_, Color color_)
    { type = type_; rect = rect_; color = color_; }
}

有一个班级List<T>

List<DrawAction> actions = new List<DrawAction>();

您可以像这样编写几个按钮:

  private void RectangleButton_Click(object sender, EventArgs e)
{
    actions.Add(new DrawAction('R', new Rectangle(11, 22, 66, 88), Color.DarkGoldenrod));
    mainPanel.Invalidate();  // this triggers the Paint event!
}


private void circleButton_Click(object sender, EventArgs e)
{
    actions.Add(new DrawAction('E', new Rectangle(33, 44, 66, 88), Color.DarkGoldenrod));
    mainPanel.Invalidate();  // this triggers the Paint event!
}

Paint事件中:

private void mainPanel_Paint(object sender, PaintEventArgs e)
{
    foreach (DrawAction da in actions)
    {
        if (da.type == 'R') e.Graphics.DrawRectangle(new Pen(da.color), da.rect);
        else if (da.type == 'E') e.Graphics.DrawEllipse(new Pen(da.color), da.rect);
        //..
    }
}

还使用双缓冲的Panel 子类

class DrawPanel : Panel
{ 
    public DrawPanel() 
    { this.DoubleBuffered = true; BackColor = Color.Transparent; }
}

接下来的步骤是添加更多类型,如线条,曲线,文字;还有颜色,笔宽和款式。同时使其动态化,以便您选择一个工具,然后单击面板..

对于徒手画,您需要在List<Point>等中收集MouseMove

很多工作,很有趣。