Sorry for my bad english.
I want to render a DrawingVisual to a bitmap so I can create a DiffuseMaterial. I do this:
public DiffuseMaterial GetDiffuseMaterial(string text, string font, double fontSize, Brush brush)
{
FormattedText formattedText = new FormattedText(text, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, new Typeface(font), fontSize, brush);
DrawingVisual drawingVisual = new DrawingVisual();
using (DrawingContext drawingContext = drawingVisual.RenderOpen())
drawingContext.DrawText(formattedText, new Point(0, 0));
RenderTargetBitmap bmp = new RenderTargetBitmap((int)(text.Length * fontSize), (int)fontSize, 96, 96, PixelFormats.Pbgra32);
bmp.Render(drawingVisual);
DiffuseMaterial mat = new DiffuseMaterial(new ImageBrush(bmp));
mat.Freeze();
return mat;
}
But...
- If I use the Method GetDiffuseMaterial 10000 times, the application stop. This is "normal" because every application can have maximum 10000 GDI handles and RenderTargetBitmap use 1 GDI handle each time it is created.
A workaround to this is to free RenderTargetBitmap object. But I didn't get to do it. I tried this (between mat.Freeze() and return mat;) :
bmp.Freeze(); bmp = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect();
Another way to do it is by having only one RenderTargetBitmap and give it as a parameter to GetDiffuseMaterial.
But if I call two times GetDiffuseMaterial, I will have two identic Materials because the handle is shared and the Materials take the last modification. (so even if the text parameter is not the same !)
I don't see another way to do what I want with RenderTargetBitmap.
NB : GetDiffuseMaterial can be called 1 million times...
RenderTargetBitmap is the fastest way I found to create a DiffuseMaterial from a String text. Other technics are really slow : using a VisualBrush with TextBlock, using a DrawingBrush, ... e.g : 5000 calls to GetDiffuseMaterial is at least 10x faster using RenderTargetBitmap than the other technics.
Thank you for your help.