views:

52

answers:

1

Hey Guys, I'm trying to generate a bitmap off a WPF border. The whole thing sits in a asp.net app (server side of course) running .net 4.0.

The problem is, that the generated image is, well, empty. Does anyone have an idea why?

Here's the code.

public static byte[] Draw(int width, int height)
    {
        MemoryStream memoryStream
            = new MemoryStream();
        Thread t = new Thread(delegate()
            {
                System.Windows.Controls.Border border = new System.Windows.Controls.Border()
                {
                    Background = Brushes.Red,
                    BorderBrush = Brushes.Green,
                    CornerRadius = new System.Windows.CornerRadius(5),
                    Width = width,
                    Height = height
                };

                border.ApplyTemplate();

                RenderTargetBitmap renderTargetBitmap = 
                    new RenderTargetBitmap(width, height, 90, 90, PixelFormats.Pbgra32);

                renderTargetBitmap.Render(border);

                BitmapEncoder bitmapEncoder = 
                    new PngBitmapEncoder();

                bitmapEncoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
                bitmapEncoder.Save(memoryStream);
            });
        t.SetApartmentState(ApartmentState.STA);
        t.Start();
        bool success = t.Join(5000);

        if (success)
            return memoryStream.ToArray();
        else
            throw new Exception("Fail");
    }

The result is quite bad, as I said the thing returns the image with the right width and height, but it's empty, so I guess I don't mess the thing up with the threading bit.

+1  A: 

Add right after border.ApplyTemplate:

border.Measure(new Size(width, height));
border.Arrange(new Rect(0, 0, width, height));
border.UpdateLayout();

Your border didn't update itself before you are saving it.

Nir
nice one, thanks mate!
Dänu