问题
We use custom fonts to represent road signs and shapes that we plot on a graph.
Initially I plotted everything to a canvas, which worked fine, but was slow to scroll horizontally.
Then I fixed the scrolling issue by converting the canvas to a image using the WriteableBitmap, like this:
#if SILVERLIGHT
ImageSource ConvertCanvas(Canvas canvas) {
WriteableBitmap Source = new WriteableBitmap(canvas, /* transform = */ null);
Source.Invalidate();
return Source;
}
#endif
This conversion works fine for most of the elements on the canvas, except the TextBlocks that use the custom font.
So, instead of the proper "custom font" images (characters), I get normal Arial characters, like 'p', 'q', etc...
If I display the canvas again instead the converted image then I can confirm that the custom font works and renders the textblock correctly, so it does not seem to be a loading issue...
Please help or give some pointers I can look into...
Thank you in advance
EDIT:
OK, I found a solution here which boils down to either 1. creating a hidden textblock that use the font before doing the conversion, or 2. creating a FontSource.
I used the first because it was simpler for now.
Inside the control, I added the following:
void Grid_Loaded(object sender, RoutedEventArgs e) {
#if SILVERLIGHT
Grid Grid = (Grid)sender;
AddFontLoaderTextBox(Grid, "Signs Road Features");
AddFontLoaderTextBox(Grid, "Signs G Old");
AddFontLoaderTextBox(Grid, "Signs G");
AddFontLoaderTextBox(Grid, "Signs G1");
AddFontLoaderTextBox(Grid, "Signs G2");
AddFontLoaderTextBox(Grid, "Signs G3");
AddFontLoaderTextBox(Grid, "Signs Info");
AddFontLoaderTextBox(Grid, "Signs Regulatory");
AddFontLoaderTextBox(Grid, "Signs Regulatory1");
AddFontLoaderTextBox(Grid, "Road Manager");
AddFontLoaderTextBox(Grid, "Signs Temporary");
AddFontLoaderTextBox(Grid, "Road Manager");
AddFontLoaderTextBox(Grid, "Signs Warning");
AddFontLoaderTextBox(Grid, "Signs Warning1");
#endif
}
#if SILVERLIGHT
void AddFontLoaderTextBox(Grid Grid, string fontName) {
TextBlock TextBlock = new TextBlock();
TextBlock.FontFamily = new FontFamily(string.Format(
"pack://application:,,,/ITIS.Controls.LinearViewer.Silverlight;component/Fonts/{0}.ttf#{0}", fontName));
TextBlock.Opacity = 0; /* hide the text block, we only load it for the font to be cached */
Grid.SetRowSpan(TextBlock, 3); /* just to ensure the text block doesn't affect the size of the first row */
Grid.Children.Insert(0, TextBlock); /* keep underneath other children */
}
#endif
来源:https://stackoverflow.com/questions/12296887/silverlight-writeablebitmap-not-converting-custom-font-correctly