首页 > 解决方案 > 有没有办法计算字体的真实高度?

问题描述

我遇到过使用垂直居中无法正确对齐文本的情况。尤其是当字体较大时(即 40)。我可以通过在顶部应用负边距来修复它,但是有没有办法以编程方式计算边距的数量?我尝试获取 FormattedText,但数字与屏幕上绘制的内容不匹配。

    <Border BorderBrush="Black" BorderThickness="1,1,1,1" Width="46" Height="46" UseLayoutRounding="True" SnapsToDevicePixels="True">
        <TextBlock FontFamily="Gadugi" Margin="0,-4,0,0" FontSize="36" Text="1" HorizontalAlignment="Center" VerticalAlignment="Center" />
    </Border>

-4 修复了这种情况,但我将如何明智地计算 -4 代码?因为它在每个字体/每个字体大小的基础上都不同。

这些数字似乎与 FormattedText 中的数字不匹配。

标签: c#wpf

解决方案


您可以尝试使用这样的几何变换:

FormattedText text = new FormattedText("Your text",
    CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
    new Typeface("Arial"), 20, Brushes.Black);
Geometry geometry = text.BuildGeometry(new Point());
double height = geometry.Bounds.Bottom - geometry.Bounds.Top;

但是,这将导致您输入的字符串的高度。这意味着“abc”的高度比“ABC”短,“ABC”比“Ay”短


推荐阅读