wpf - 与 DrawingContext.DrawText 垂直对齐

标签 wpf text alignment drawingcontext

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

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

有人知道怎么做吗?

最佳答案

如果您使用的是 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);

关于wpf - 与 DrawingContext.DrawText 垂直对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25308612/

相关文章:

未针对 ContentControl 派生类型调用 WPF DataTemplateSelector.SelectTemplate

javascript - 输入文本框以及输入效果不断被删除

css - 文本忽略底部填充,无论如何绘制下一行

android - 如何在 RelativeLayout 中的 View 之间添加空间

c# - 设置TabControl的背景颜色

wpf - 将高 DPI 图像转换为低 DPI 进行打印抛出 OutOfMemoryException

python - 从 nltk word_tokenize 获取原始文本的索引

java - 如何在 java 模式下配置 emacs,使其不会自动对齐方法参数

CSS 水平对齐 float

c# - 如何在 WPF 中按名称查找样式触发器嵌入元素?