I am looking to render a DrawingVisual
(visual in the example) to a bitmap using RenderTargetBitmap
with the view to set this bitmap as the background to a Canvas
as below:
var bmp = new RenderTargetBitmap(2000, 50, 120, 96, PixelFormats.Indexed2);
bmp.Render(visual);
var brush = new ImageBrush(bmp) { Stretch = Stretch.Fill };
Canvas.Background = brush;
When using PixelFormats.Default
as the last argument to RenderTargetBitmap
, the image renders as expected. However, when I choose PixelFormats.Indexed2
(or any of the PixelFormats.IndexedX
), my code seems to exit the method without an exception, the bmp.Render
line is never called and hence the image is not displayed on the Canvas
.
How to use the IndexedX
pixel formats with RenderTargetBitmap
? Or are there other ways to reduce the memory footprint of the image? It only uses three colors, so using a palette rather than 32bit RGB seemed the way to go.
You can't. RenderTargetBitmap
only supports the Pbgra32
pixel format. That's because WPF's rendering system works entirely in 32 bits per pixel. That's the format in which it generates images, and it's also the format in which it prefers images to be in if you want to render them. (If you provide it with a bitmap in any other format, it'll need to convert it into a 32 bit per pixel representation first.)
What are you planning to do with this bitmap? If you want to render it in a WPF application, it'll need to be converted to a 32bpp format first in any case, so you risk using more memory if you attempt to hold it internally in any other format. (You'll have your supposedly memory-efficient representation and the version WPF's actually able to work with.) Not to mention the extra CPU time spent converting between your chosen format and a format WPF can work with.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With