在DrawingImage内绘制格式化文本

5

我想在XAML图形中包含一些格式化的文本。这是否可行?如何实现?

例如:

<DrawingImage>
    <DrawingImage.Drawing>
      <!-- Can text be drawn here? -->
    </DrawingImage.Drawing>
</DrawingImage>
2个回答

9
<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
但是如何正确设置RectangleGeometry以避免文本拉伸? - SKINDER
很好的答案。我认为这是使用XAML完成它的最佳解决方案。谢谢。 - Mathias Müller

2
是的。使用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;
}

非常有帮助。我已经看过XAML中的示例,但不知道如何连接AdvanceWidths和Height。有什么想法吗? - Brian Triplett
连接它们的意思是什么? - Ed Bayiates
在您的代码后台中,AdvanceWidths和glyphIndicies是在for循环中设置的。我不知道如何在XAML中表示它。 - Brian Triplett
1
在Xaml中,它们只是带引号的数字列表:GlyphIndices="43 72 79" AdvanceWidths="9.62 7.41 2.96" - Ed Bayiates
我在MSDN的文档中看到了这个。你有什么想法如何找出“正确”的值吗?我已经找出了我的文本的索引,但不知道如何获取我的字体(Segoe UI)中各个字符的AdvanceWidths。 - Brian Triplett
1
这就是为什么我为您包含了代码后台。您可以为每个计算值插入System.Diagnostics.Debug.WriteLine,并从调试器输出窗口获取结果。 - Ed Bayiates

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接