在DrawText中设置垂直对齐方式

6
我正在使用DrawText在可视层上绘制FormattedText。现在我正在使用以下代码来定义格式化文本,并且我能够将TextAlignment设置为Center。但是VerticalAlignment怎么样呢?如下图所示,文字的中心不在这里显示的中心点上,该点用红点标出。 我定义FormattedText的部分:
var ft = new FormattedText("A",
    CultureInfo.GetCultureInfo("en-us"),
    FlowDirection.LeftToRight,
    new Typeface("Verdana"),
    36, Brushes.Yellow);

ft.TextAlignment = TextAlignment.Center;

我正在绘制文本的部分:
var centerpoint = new Point(0,0);
dc.DrawText(ft, centerpoint);

这是最终结果:

enter image description here

我希望文本的中心位于圆的中心。

2个回答

8

好的,看起来我已经成功解决了这个问题。 这并不难。 我将在此发布答案供未来参考。 它可能也有助于其他人。

由于似乎没有FormattedTextVerticalAlignment,因此我们需要自己计算和定位它。 由于我们可以获得格式化文本的Height属性,所以我们可以轻松地对齐文本,如下所示:

dc.DrawText(ft, new Point(centerpoint.X, centerpoint.Y- ft.Height/2));

Here is the result


0

FormattedText的最新版本,带有PixelsPerDip

Typeface typeFace = new Typeface(new FontFamily("Segoe UI"), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
FormattedText formattedText = new FormattedText("Bodrum Bodrum", CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, typeFace, 14, Brushes.Black, VisualTreeHelper.GetDpi(this).PixelsPerDip);

Point textPoint = new Point(100, 100);
drawingContext.DrawText(formattedText, textPoint);

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