2016-02-05 40 views
3

我正試圖通過單擊按鈕來製作一個程序,以在Panel(正方形,圓形等)上繪製。通過單擊WinForms中的按鈕在面板上繪圖

到目前爲止,我還沒有做很多工作,只是試着直接將代碼繪製到面板上,但不知道如何將其移動到按鈕上。這是我迄今爲止的代碼。

如果你知道比我使用的更好的繪製方法,請告訴我。

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

}

+1

初學者:This:'Graphics g; g = CreateGraphics();'應該是:'g = e.Graphics'!並繪製不同的東西,你需要收集列表這些東西,並繪製它們都在'Paint'事件..看到[這裏](http://stackoverflow.com/search?q=user%3A3152130+drawaction)我的幾篇文章討論瞭如何通過創建drawAction類來實現winforms中的圖形! ' – TaW

回答

2

使用這個非常簡單的例子類..:

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

擁有一流水平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; } 
} 

下一步驟將是添加更多的類型,如線,曲線,文字;還有顏色,筆寬和樣式。也使其動態,讓你選擇一個工具,然後單擊面板..

徒手繪製你需要收集在MouseMove等一個List<Point> ..

很多工作,很多的樂趣。

+0

嗨,謝謝你的幫助,我開始了所有的時候,當我試圖讓課堂'DrawAction'我得到一個錯誤,因爲它無法識別'矩形'或'顏色'...我應該聲明它們? –

+0

如果您是從頭開始創建的,您應該在新文件中包含必要的'using'子句;在這裏你缺少'使用System.Windows.Forms;'可能有其他人! – TaW

+0

是的,我做過。我爲它工作了大約3天,它正在工作,現在我試圖讓用戶選擇顏色。非常感謝你的幫助。 –