WPF: Fast drawing/scaling of complex image
I'm drawing a complex image that consist of hundreds of GeometryDrawing objects. The drawing is quite fast, but rescaling is slow. I can imagine that redrawing hundreds of object takes some time. As a solution,开发者_运维百科 I want to turn my drawing into a bitmap.
I've tried the following, but this doesn't work. The result image is blank.
private Image CreateBitmapImage(DrawingImage drawingImage)
{
var image = new Image()
image.Source = drawingImage;
var bitmap = new RenderTargetBitmap(300, 300, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(image);
image.Source = bitmap;
return image;
}
How can I turn a DrawingImage into a bitmap?
If you are using RenderTargetBitmap with newly created elements you need to make sure you call Measure and Arrange.
private Image CreateBitmapImage(DrawingImage drawingImage)
{
var image = new Image();
image.Source = drawingImage;
var bitmap = new RenderTargetBitmap(300, 300, 96, 96, PixelFormats.Pbgra32);
var size = new Size(bitmap.PixelWidth,bitmap.PixelHeight);
image.Measure(size);
image.Arrange(new Rect(size));
bitmap.Render(image);
image.Source = bitmap;
return image;
}
You will probably want to pass the size in as a parameter and it might be better to return the RenderTargetBitmap instead of an Image element so you can use it in multiple places.
WPF has some features that you might want to look into such as Freezables, BitmapCache and CachingHint for TileBrushes however RenderTargetBitmap is still a good choice as it is predictable.
精彩评论