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

标签 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)
    {
    }
}

最佳答案

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

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/

相关文章:

c# - 从手机方向更改中锁定特定的 UI 项目?

c# - 使用 Entity Framework 的具有多对多关系的 Linq 查询

c++ - Visual Studio C++ 2015 Update 3 中的 abs(complex) 出现奇怪问题

c# - VSCT 未定义 'Parent/@id' 属性

c# - 您如何指定特定的第 3 组 tiff 压缩?

c# - C#中的定时器问题

c# - 将值从标签放入 excel 列的简短或简单的解决方案

c# - 获取跨线程操作在 SetWindowPos() 中无效

node.js - Gulp 没有将 scss 转换为 css

visual-studio - TFS2010 : Fast way to determine user, 谁编辑了 "this function"或 "this line of code"?