I'm trying 开发者_StackOverflow社区to include some formatted text as part of a drawing in XAML. Is this possible? How is it done?
Example:
<DrawingImage>
<DrawingImage.Drawing>
<!-- Can text be drawn here? -->
</DrawingImage.Drawing>
</DrawingImage>
<DrawingImage>
<DrawingImage.Drawing>
<GeometryDrawing>
<GeometryDrawing.Geometry>
<RectangleGeometry Rect="0,0,10,10"></RectangleGeometry>
</GeometryDrawing.Geometry>
<GeometryDrawing.Brush>
<VisualBrush>
<VisualBrush.Visual>
<StackPanel>
<TextBlock Text="Tyco" FontSize="16" FontWeight="999" Foreground="Black"></TextBlock>
</StackPanel>
</VisualBrush.Visual>
</VisualBrush>
</GeometryDrawing.Brush>
</GeometryDrawing>
</DrawingImage.Drawing>
</DrawingImage>
Yes. Use a GlyphRunDrawing as part of the DrawingGroup or as the Drawing itself, that is the source of your DrawingImage. To construct the GlyphRun in Xaml is possible, and also in code behind:
Typeface typeface = new Typeface(FontFamily, FontStyle, FontWeight, FontStretches.Normal);
if (!typeface.TryGetGlyphTypeface(out _glyphTypeface))
return;
_glyphIndexes = new ushort[text.Length];
_advanceWidths = new double[text.Length];
double textWidth = 0;
for (int ix = 0; ix < text.Length; ix++)
{
ushort glyphIndex = _glyphTypeface.CharacterToGlyphMap[text[ix]];
_glyphIndexes[ix] = glyphIndex;
double width = _glyphTypeface.AdvanceWidths[glyphIndex] * FontSize;
_advanceWidths[ix] = width;
textWidth += width;
double textHeight = _glyphTypeface.Height * FontSize;
}
精彩评论