2011-09-16 39 views
1

我一直在學習如何使用GDI,但我很難理解Invalidate()如何重載onPaint事件並且看起來好像繞圈了一圈。用GDI繪製線條失效()/ onPaint問題

我有以下代碼

private void DrawLine() 
{ 
    System.Drawing.Pen myPen = new System.Drawing.Pen(System.Drawing.Color.Red); 
    System.Drawing.Graphics formGraphics; 
    formGraphics = this.CreateGraphics(); 
    formGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; 
    formGraphics.DrawLine(myPen, mouseDown.X, mouseDown.Y, mouseUp.X, mouseUp.Y); 
    myPen.Dispose(); 
    formGraphics.Dispose(); 
} 

protected override void OnPaint(PaintEventArgs e) 
{ 
    DrawLine(); 
} 

private void Form1_MouseDown(object sender, MouseEventArgs e) 
{ 
    mouseDown = e.Location; 

} 

private void Form1_MouseUp(object sender, MouseEventArgs e) 
{ 
    mouseUp = e.Location;   
} 

不過,我可以得到我剛剛繪製出現行的唯一方法是手動調用的Invalidate(),當我這樣做是清除任何以前的行。任何人都可以告訴我我要去哪裏嗎?

回答

1

它改成這樣:

Bitmap bmp = new Bitmap(256, 256); 

protected override void OnPaint(PaintEventArgs e) 
{ 
    e.Graphics.DrawImage(bmp, new Point(0, 0)); 
} 

private void Form1_MouseDown(object sender, MouseEventArgs e) 
{ 
    mouseDown = e.Location; 
} 

private void Form1_MouseUp(object sender, MouseEventArgs e) 
{ 
    mouseUp = e.Location; 
    using (Graphics g = Graphics.FromImage(bmp)) 
    { 
    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; 
    g.DrawLine(Pens.Red, mouseDown.X, mouseDown.Y, mouseUp.X, mouseUp.Y); 
    } 
    this.Invalidate();   
} 

OnPaint方法提供了您用來繪製圖形的畫布。實際上,你很少需要自己調用CreateGraphics。 MouseUp上的Invalidate()調用告訴您的控件調用OnPaint事件。

+0

感謝您的回答,它效果很好,但是當我畫一條線時,屏幕上的任何以前的線都會被擦除。還有什麼我失蹤? – GrandMasterFlush

+0

@GrandMasterFlush你需要一個位圖。我會馬上更新。 – LarsTech

+0

非常感謝您抽出時間發帖,我整個上午都一直圍着這個圈子走。這解釋了很多。 – GrandMasterFlush

1

讓您的DrawLine採取Graphics參數:

public void DrawLine(Graphics g) { 
//... 
} 

在OnPaint中,利用從E顯卡:

protected override void OnPaint(PaintEventArgs e) 
{ 
    DrawLine(e.Graphics); 
} 

在的MouseUp再次調用DrawLine的與圖形的的背景圖像對象形式:

private void Form1_MouseUp(object sender, MouseEventArgs e) 
{ 
    mouseUp = e.Location; 
    DrawLine(Graphics.FromImage(BackgroundImage)); 
    Invalidate(); 
} 

添加MouseMove方法:

private void Form1_MouseMove(object sender, MouseEventArgs e) 
{ 
    mouseUp = e.Location; 
    Invalidate(); 
} 

可選的是,爲了清楚起見,將mouseDown重命名爲StartPoint和mouseUp - EndPoint。