Is there a way to calculate the REAL height of a font?

Viewed 62

I've ran across a situation where text doesn't align properly using the vertical centering. Especially when the font size is large (i.e. 40). I can fix it by applying a negative margin to the top, but is there a way to programmatically calculate the amount of the margin? I tried getting the FormattedText, but the numbers just don't match up with what's drawn on the screen.

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

The -4 fixes this case, but how would I calculate the -4 code wise? Since it's different on a per font / per font size basis.

The numbers just don't seem to match up with what's in FormattedText.

1 Answers

You could try using geometry transformation like this:

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;

However this will result in the height of the string you input. This means that "abc" is shorter in height than "ABC" which is shorter than "Ay"

Related