2017-03-24 54 views
1

我有以下代碼:RenderTargetBitmap似乎並沒有使我的矩形

 LinearGradientBrush linGrBrush = new LinearGradientBrush(); 
     linGrBrush.StartPoint = new Point(0,0); 
     linGrBrush.EndPoint = new Point(1, 0); 
     linGrBrush.GradientStops.Add(new GradientStop(Colors.Red, 0.0)); 
     linGrBrush.GradientStops.Add(new GradientStop(Colors.Yellow, 0.5)); 
     linGrBrush.GradientStops.Add(new GradientStop(Colors.White, 1.0)); 

     Rectangle rect = new Rectangle(); 
     rect.Width = 1000; 
     rect.Height = 1; 
     rect.Fill = linGrBrush; 
     rect.Arrange(new Rect(0, 0, 1, 1000)); 
     rect.Measure(new Size(1000, 1)); 

如果我做

myGrid.Children.Add(rect); 

則漸變繪製精細的窗口。

我想在其他地方使用此漸變強度圖,所以我需要從中獲取像素。要做到這一點,我明白我可以將它轉換爲位圖,使用RenderTargetBitmap。下面的代碼的下一個部分:

 RenderTargetBitmap bmp = new RenderTargetBitmap(
      1000,1,72,72, 
      PixelFormats.Pbgra32); 
     bmp.Render(rect); 

     Image myImage = new Image(); 
     myImage.Source = bmp; 

爲了驗證這一點,我做的:

myGrid.Children.Add(myImage); 

但沒有出現在窗口上。我究竟做錯了什麼?

+0

確實[這](http://stackoverflow.com/questions/11237524/is-it-possible-to-brush-a -drawingvisual)和[msdn](https://msdn.microsoft.com/en-us/library/system.windows.media.imaging.rendertargetbitmap(v = vs.110).aspx)所以幫助 –

回答

2

Arrange必須在Measure之後調用,並且Rect值應該正確傳遞。取而代之的

rect.Arrange(new Rect(0, 0, 1, 1000)); // wrong width and height 
rect.Measure(new Size(1000, 1)); 

你應該做的

var rect = new Rectangle { Fill = linGrBrush }; 
var size = new Size(1000, 1); 
rect.Measure(size); 
rect.Arrange(new Rect(size)); 

var bmp = new RenderTargetBitmap(1000, 1, 96, 96, PixelFormats.Pbgra32); 
bmp.Render(rect); 
相關問題