【问题标题】:Set VerticalAlignment in DrawText在 DrawText 中设置 VerticalAlignment
【发布时间】:2014-05-11 21:25:15
【问题描述】:

我正在使用DrawText 在可视层上绘制FormattedText。现在我使用下面的代码来定义格式化的文本,我可以将TextAlignment 设置为Center。但是VerticalAlignment 呢?正如您在下图中看到的,文本的中心不在 centerpoint 上,此处用红点显示。

我定义 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);

这是最终结果:

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

【问题讨论】:

    标签: c# wpf vertical-alignment drawtext


    【解决方案1】:

    好吧,看来我能够解决这个问题。这并不难。我将在此处发布答案以供将来参考。它也可能对其他人有所帮助。

    对于FormattedText,似乎没有VerticalAlignment 这样的东西,所以我们需要自己计算和定位。因为我们可以得到格式化文本的Height 属性。我们可以像这样轻松地对齐文本:

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

    【讨论】:

      【解决方案2】:

      FormattedTextPixelsPerDip. 的最新版本

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

      【讨论】:

        猜你喜欢
        • 2012-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-11
        • 2011-03-23
        • 1970-01-01
        • 2013-03-17
        相关资源
        最近更新 更多