通过单击的WinForms一个按钮,绘制一个面板上 [英] Drawing on a panel by clicking a button in WinForms

查看:125
本文介绍了通过单击的WinForms一个按钮,绘制一个面板上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过点击一个按钮来使程序上绘制一个面板(方形,圆形等)。

I'm trying to make a program to draw on the a Panel (a square, circle, etc...) by clicking on a button.

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

I have not done much so far, just tried the code drawing directly to the panel but don't know how to move it to the button. Here is the code I have so far.

如果你知道一个更好的方法比我使用,请让我知道一画。

If you know a better method to draw than the one I'm using please let me know.

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

}

推荐答案

使用这个非常简单的例子类..:

Using this extremely simplified example class..:

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



拥有一流水平的列表< T>

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

您会编写这样的几个按钮:

you would code a few buttons like this:

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



而在油漆事件:

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



接下来的步骤将是添加更多的类型,如线条,曲线,文本;还颜色,笔宽和风格。也使它充满活力,让你选择一个工具,然后单击面板。

The next steps will be to add more types, like lines, curve, text; also colors, pen widths and styles. Also make it dynamic, so that you pick a tool and then click at the Panel..

有关写意画,你需要收集列表<点> 的MouseMove

For freehand drawing you need to collect a List<Point> in the MouseMove etc..

很多工作,很多的乐趣

这篇关于通过单击的WinForms一个按钮,绘制一个面板上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆