3

我有以下代码:

        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);

但是窗户上什么也没有。我究竟做错了什么?

4

1 回答 1

4

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);
于 2017-03-24T10:17:45.520 回答