3

I have the following code:

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

If I do

 myGrid.Children.Add(rect);

Then the gradient is drawn fine on the window.

I want to use this gradient for an intensity map somewhere else, so I need to get the pixels out of it. To do this, I understand I can convert it to a bitmap, using RenderTargetBitmap. Here's the next part of the code:

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

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

To test this, I do:

myGrid.Children.Add(myImage);

But nothing appears on the window. What am I doing wrong?

0

1 Answer 1

4

Arrange has to be called after Measure, and the Rect values should be passed correctly.

Instead of

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

you should do

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.