2009-07-01 76 views
2

當我運行下面的代碼:C#,GDI + - 爲什麼我的矩形被截斷?

private void button1_Click(object sender, EventArgs e) 
    { 
     Bitmap b = new Bitmap(300, 400); 
     using (Graphics g = Graphics.FromImage(b)) 
     { 
      g.FillRectangle(Brushes.Black, new Rectangle(0, 0, 300, 400)); 
     } 

     b.RotateFlip(RotateFlipType.Rotate90FlipNone); 

     using (Graphics g2 = Graphics.FromImage(b)) 
     { 
      g2.DrawRectangle(new Pen(Color.White, 7.2f), 200, 100, 150, 100); 
     } 

     using (Graphics g3 = this.panel1.CreateGraphics()) 
     { 
      g3.DrawImage(b, 0, 0); 
     } 
    } 

我得到如下:

alt text http://www.freeimagehosting.net/uploads/2c309ec21c.png

注:

  • 它只有當我旋轉圖像發生了,再畫延伸超過圖像尺寸的原始的矩形。

  • 矩形不會被截斷爲原始圖像的寬度 - 只是矩形的右邊緣沒有繪製。

  • 這發生在各種情況下。我首先在一個更復雜的應用程序中注意到它 - 我只是寫了這個應用程序來簡單說明問題。

任何人都可以看到我做錯了什麼?

回答

7

這似乎是Microsoft自從2005年以來已知曉的GDI +錯誤(http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=96328)。我能夠重現你描述的問題。一種可能的解決方案是從第一個位圖創建第二個位圖,並借鑑它。下面的代碼似乎正確繪製:

private void button1_Click(object sender, EventArgs e) { 
    Bitmap b = new Bitmap(300, 400); 
    using (Graphics g = Graphics.FromImage(b)) { 
     g.FillRectangle(Brushes.Black, new Rectangle(0, 0, 300, 400)); 
    } 

    b.RotateFlip(RotateFlipType.Rotate90FlipNone); 
    Bitmap b2 = new Bitmap(b); 

    using (Graphics g2 = Graphics.FromImage(b2)) { 
     g2.DrawRectangle(new Pen(Color.White, 7.2f), 200, 100, 150, 100); 
    } 

    using (Graphics g3 = this.panel1.CreateGraphics()) { 
     g3.DrawImage(b2, 0, 0); 
    } 
} 

alt text http://www.freeimagehosting.net/uploads/f6ae684547.png

+0

真棒 - 非常感謝! – mbeckish 2009-07-01 18:50:05

0

你的問題是DrawRectangle。矩形的起始位置到達您的初始位圖的末尾。

如果更改矩形的位置,您將能夠完全看到它。

using (Graphics g2 = Graphics.FromImage(b)) 
{ 
    g2.DrawRectangle(new Pen(Color.White, 7.2f), 50, 50, 150, 100); 
} 
+0

我不能改變矩形的位置 - 我想那裏繪製。如果切換斷點,則可以看到在繪製矩形之前,位圖和圖形g2都獲得了新的尺寸。 – mbeckish 2009-07-01 18:39:39

0

我試着用TryGdiPlus你的代碼(非常有用的這類事情,BTW)。 我設法讓矩形畫沒有99個像素寬剪裁:

g2.DrawRectangle(new Pen(Color.White, 7.2f), 200, 100, 99, 100); 

所以它看起來好像位圖的寬度仍然是300個像素,甚至旋轉之後。

+0

如果您切換斷點,則可以看到在繪製矩形之前,位圖和圖形g2都獲得了新維度。 – mbeckish 2009-07-01 18:40:17