In my WPF application I have a custom Canvas implementation, in which I draw some text using a specified .ttf file. The ttf file resides in a temporary location that can be deleted at some later point in time. My problem is that once my text has been rendered on the canvas, the ttf file seems to be kept open, and can't be deleted until the application has been closed down. Is seems to be the FormattedText instance that keeps the font file open. Does anybody know a way to "Dispose" the FormattedText, or in any other way make sure that the font file is closed after rendering?
My text drawing code:
public class MyCanvas : System.Windows.Controls.Canvas
{
protected override void OnRender(DrawingContext dc)
{
base.OnRender(dc);
// Some other drawing stuff...
FontFamily fontFamily = new FontFamily(fontUri);
Typeface typeFace = new Typeface(fontFamily, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
FormattedText formattedText = new FormattedText(chars, System.Globalization.CultureInfo.InvariantCulture, FlowDirection.LeftToRight, typeFace, text.FontHeight, new SolidColorBrush(color));
dc.DrawText(formattedText, new Point(text.X + offsetX, text.Y + offsetY));
int textWidth = (int) formattedText.Width;
int textHeight = (int)formattedText.Height;
// Drawing continues...
}
}
Note: It seems I don't even have to call DrawText
to lock the font file (tried commenting that line out). Using the formattedText instance to assign the textWidth and textHeight variables is enough for WPF to keep the file open.
Update: I've not been able to solve this problem, so currently I'm using a workaround that creates a new temporary font directory if overwriting the existing one fails. It works, but I'm not very happy with having to do it like this, so I'm still interested in any suggestions how to fix this.