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

我正在尝试通过单击按钮制作一个程序来绘制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) { } } 

}

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

 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_; } } 

有一个class级List

 List actions = new List(); 

你会像这样编码几个按钮:

  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; } } 

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

对于徒手绘图,您需要在MouseMove等中收集List

很多工作,很有趣。