我正在尝试制作一个程序,通过单击按钮在 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<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
等..
很多工作,很多乐趣。
评论更新:
注意:这是因为我写的极其简化。我有能力绘制矩形和椭圆形等形状。使用更多代码,您可以为填充矩形和填充椭圆添加更多字符。但是 a) 形状确实应该在枚举中并且 b) 更复杂的形状,如线条、多边形、文本或旋转的形状将需要更多的数据,而不仅仅是一个矩形。 .
对矩形坐标的限制是一种简化,与其说是形状的简化,不如说是数据结构的简化。您的其他形状可以缩小以适合矩形(想到四个三角形和两个六边形);只需添加字符和新的 drawxxx 调用。但是最终为复杂形状添加一个列表,也许字符串和字体将允许更复杂的结果。
关于c# - 通过单击 WinForms 中的按钮在面板上绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35219758/