2014-10-06 330 views
5

我在控制區重複繪製一些圖形,每次我都想用透明背景重新開始。所以我用:C#Graphics.Clear(Color.Transparent)無法正常工作?

Graphics graph = control.CreateGraphics(); 
graph.Clear(Color.Transparent); 

但是,圖形區域似乎變成黑色而不是透明。有任何想法嗎?

+2

像Clear這樣的圖形函數在與Color.Transparent一起使用時基本上是no-ops。 'graphics.Clear(Color.Transparent)'並不意味着「讓我的整個圖形空間透明」。相反,它意味着,「通過在當前空間上繪製'透明'顏色來清除我的整個圖形空間。」 – 2014-10-06 20:16:59

+0

要診斷它爲什麼會變黑,我們可能需要更多信息。這是否在Paint事件處理程序中的自定義控件中?你是否設置了任何ControlStyles? – 2014-10-06 20:18:16

+0

然後在'OnPaint'覆蓋中做你的痛苦...避免'CreateGraphics' ...這是邪惡的。 – DonBoitnott 2014-10-06 20:18:24

回答

2

我找到了一種替代方法來實現我所需要的。我創建控件的尺寸新的透明位圖,畫我的東西就可以了,然後用它作爲控制背景圖片:

Bitmap bitmap = new Bitmap(control.Width, control.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); 
    bitmap.MakeTransparent(); 
    Graphics graph = Graphics.FromImage(bitmap); 

    // draw stuff here ... 

    control.BackgroundImage = bitmap; 
    graph.Dispose(); 

這完美的作品。

+1

如果您使用語句創建實現IDisposable接口的對象,那更好。這樣做的好處是,你不必管理物體的處理。 因此,爲清潔實施變更 Graphics graph = Graphics.FromImage(bitmap); 到 使用(Graphics graph = Graphics.FromImage(bitmap)) { //在這裏畫東西... control.BackgroundImage = bitmap; } – Dom84 2014-10-07 11:46:45

+0

在我的情況下,我還需要做'graph.Clear(Color.Transparent);'使其工作。但是,謝謝你的回答! – 2017-02-09 15:30:22

0

因爲picturebox沒有透明圖層。你可以使用傳輸位圖。 試試這個。

 tmp_bmp = new Bitmap(picturebox1.Width, picturebox1.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); 
     Graphics Canvas = Graphics.FromImage(tmp_bmp); 
     picturebox1.Image = tmp_Type; 

     Type_Canvas.Clear(Color.Transparent);