C# 通过单击WinForms中的按钮在面板上绘图
我正试图通过点击按钮制作一个程序,在aC# 通过单击WinForms中的按钮在面板上绘图,c#,winforms,visual-studio,C#,Winforms,Visual Studio,我正试图通过点击按钮制作一个程序,在a面板上绘制(正方形、圆形等) 到目前为止,我还没有做很多工作,只是尝试将代码直接绘制到面板上,但不知道如何将其移动到按钮上。这是我到目前为止的代码 如果你知道比我现在用的更好的画法,请告诉我 public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void mainPanel_Paint(obj
面板上绘制(正方形、圆形等)
到目前为止,我还没有做很多工作,只是尝试将代码直接绘制到面板上,但不知道如何将其移动到按钮上。这是我到目前为止的代码
如果你知道比我现在用的更好的画法,请告诉我
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_; }
}
有一个班级级别的列表
:
在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);
//..
}
}
同时使用双缓冲面板
子类:
class DrawPanel : Panel
{
public DrawPanel()
{ this.DoubleBuffered = true; BackColor = Color.Transparent; }
}
下一步将添加更多类型,如直线、曲线、文本;还有颜色、笔宽和样式。还可以将其设置为动态,以便拾取一个工具,然后单击面板
对于徒手画,您需要在鼠标移动
等中收集列表
很多工作,很多乐趣
评论更新:
注意:正如我所写的,这是非常简单的。我有画矩形和椭圆的性格。只要代码多一点,就可以为填充矩形和填充椭圆添加更多字符。但是a)形状确实应该在枚举中,b)更复杂的形状,如直线、多边形、文本或旋转形状,需要的数据比矩形更多
对矩形坐标的限制是一种简化,不是形状的简化,而是数据结构的简化。你的其他形状可以缩小成一个矩形(四个三角形和两个六边形);只需添加字符和新的drawxxx调用。。但实际上,为复杂的形状添加一个列表,或者添加一个字符串和一个字体,将获得更复杂的结果。对于初学者来说:这是:Graphics g;g=CreateGraphics()代码>应该是:g=e.Graphics
!要绘制不同的东西,您需要将这些东西收集到一个列表中,并在Paint
事件中绘制它们。。请参阅我的几篇文章,其中讨论了通过创建drawAction类在winforms中进行图形处理的方法`您好,谢谢您的帮助,我从头开始,当我尝试创建类“DrawAction”时,我得到一个错误,因为它无法识别“矩形”或“颜色”。。。我应该在哪里声明它们?如果您是从头开始创建的,您应该在新文件中使用
子句包含必要的;这里缺少使用System.Windows.Forms的代码>可能还有其他人!是的。我花了大约3天的时间来制作它,现在我正在尝试让用户选择颜色。非常感谢你的帮助。我试着给你的答案投赞成票,但我不能,因为我需要有更多的声誉来做到这一点,对不起。是的,需要15分。然而,如果你发现它对解决你的问题有用,你可以
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);
//..
}
}
class DrawPanel : Panel
{
public DrawPanel()
{ this.DoubleBuffered = true; BackColor = Color.Transparent; }
}