在DrawingImage中绘制格式化文本

时间:2011-07-15 19:27:52

标签: wpf drawing

我正在尝试在XAML中包含一些格式化文本作为绘图的一部分。这可能吗?怎么做?

示例:

<DrawingImage>
    <DrawingImage.Drawing>
      <!-- Can text be drawn here? -->
    </DrawingImage.Drawing>
</DrawingImage>

2 个答案:

答案 0 :(得分:5)

<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>

答案 1 :(得分:1)

是。使用GlyphRunDrawing作为DrawingGroup的一部分或作为Drawing本身,这是DrawingImage的源。在Xaml中构造GlyphRun是可能的,也可以在代码后面:

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;
}