2015-03-31 171 views
0

當我創建一個這樣的:WPF創建透明WriteableBitmap的

WriteableBitmap wb = new WriteableBitmap(1200, 1600, 90, 90, PixelFormats.Bgr24, null); 

其填充爲黑色時,我希望它是透明的。我嘗試了Clear(來自WriteableBitmapEx庫),但我試圖讀取或寫入受保護的內存。這通常是指示其他內存已損壞「} {System.Exception的} System.AccessViolationException

wb.Clear(Colors.Transparent); 

任何想法我怎麼能做到這一點

編輯:?

 List<FormattedText> text = new List<FormattedText>(); 
     WriteableBitmap wb = new WriteableBitmap(1200, 1600, 96, 96, PixelFormats.Bgr32, null); 
     wb.Clear(Colors.Transparent); 

     TransformedBitmap tb = new TransformedBitmap(wb, new RotateTransform(0)); 
     DrawingVisual drawingVisual = new DrawingVisual(); 
     DrawingContext drawingContext = drawingVisual.RenderOpen(); 
     drawingContext.DrawImage(tb, new Rect(0, 0, tb.PixelWidth, tb.PixelHeight)); 



     for (int i = 0; i < text.Count; i++) 
     { 

      drawingContext.DrawText(text[i], points[i]); 
      drawingContext.DrawEllipse(null, new Pen(new SolidColorBrush(Colors.Aqua), 3), points[i], 10, 10); 
     } 

     drawingContext.Close(); 

     System.Windows.Media.Imaging.RenderTargetBitmap bmp = new System.Windows.Media.Imaging.RenderTargetBitmap(tb.PixelWidth, tb.PixelHeight, 96, 96, PixelFormats.Pbgra32); 
     bmp.Render(drawingVisual); 

     Image = bmp; 

回答

0

創建帶有Alpha通道並因此允許透明度的PixelFormat的WriteableBitmap,例如:PixelFormats.Bgra32

var wb = new WriteableBitmap(1200, 1600, 96, 96, PixelFormats.Bgra32, null); 

現在,您每像素有四個字節,一個用於藍色,一個用於綠色,一個用於紅色,另一個用於alpha值。

另請注意,對於DPI參數,您通常會使用值96

+0

你說得對。但由於某種原因它仍然是黑色的。我會發布更多的代碼。 – shady 2015-03-31 19:40:15

+0

Bgr32不是我想要的嗎? – shady 2015-03-31 19:49:40

+0

不,它是'Bgra32',代表** B ** lue,** G ** reen,** R ** ed,** A ** lpha。 – Clemens 2015-03-31 19:53:11