与DrawingContext.DrawText垂直对齐

时间:2014-08-14 12:57:29

标签: wpf text alignment drawingcontext

我需要将文本垂直对齐到顶部或底部或中心。有水平对齐的FormattedText.TextAlignment属性,但没有用于垂直对齐。

要明确Google不理解的内容:我对旋转文本垂直流动不感兴趣。我知道该怎么做。我只想让(可能是多行)文本在中心点的上方或下方或中间对齐。

有人知道怎么做吗?

1 个答案:

答案 0 :(得分:6)

如果您使用DrawingContext.DrawText方法,则必须指定文本所在的Point。这意味着你必须自己计算对齐。

小例子,假设centerPoint是您希望文字与之对齐的点,drawingContextDrawingContext,将文字置于该点上方:

Typeface typeface = new Typeface(new FontFamily("Segoe UI"), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
FormattedText formattedText = new FormattedText("Text to render", CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, typeFace, 16, Brushes.Black);

Point textLocation = new Point(centerPoint.X - formattedText.WidthIncludingTrailingWhitespace / 2, center.Y - formattedText.Height);
drawingContext.DrawText(formattedText, textLocation);