2017-03-24 26 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);