RenderTargetBitmap 似乎没有渲染我的矩形

RenderTargetBitmap doesn't seem to render my rectangle

我有以下代码:

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

然后渐变在window.

上画的很好

我想将此渐变用于其他地方的强度图,因此我需要从中提取像素。为此,我知道我可以使用 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);

但是 window 上什么也没有出现。我做错了什么?

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