gpt4 book ai didi

c# - RenderTargetBitmap 似乎没有渲染我的矩形

转载 作者:行者123 更新时间:2023-11-30 21:41:44 24 4
gpt4 key购买 nike

我有以下代码:

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

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

最佳答案

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

关于c# - RenderTargetBitmap 似乎没有渲染我的矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42989444/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com