Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange text scaling when system font is 125%

Tags:

c#

.net

wpf

Here is full application xaml:

< Window x:Class="WpfApplication30.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Width="525"
        Height="350">
  < Border VerticalAlignment="Center"
          BorderBrush="Green"
          BorderThickness="1">
    < TextBlock Text="HELLO WORLD!"
               VerticalAlignment="Center"
               FontSize="16" />
  </Border>
</Window>

When system font is set to 125% text is not in the center of the border. There is 7 pixels between top border and text and only 4 pixels between bottom border and text. How can I fix it?

UPD: added

UseLayoutRounding="True"
SnapsToDevicePixels="True"

but diffrenece is still here: 8px and 6px

like image 763
Mikhail Gubanov Avatar asked Feb 25 '14 11:02

Mikhail Gubanov


1 Answers

Font vertical centering is complicated, as the TextBlock will align to the center of the provisioned space so that any character from your selected Font fits this area. A basic overview why this is, can be found in the Wikipedia Baseline (typography) article

You can try to compensate for the specific font's metrics by using

  • GetEmHeight(FontStyle)
  • GetCellAscent(FontStyle)
  • GetCellDescent(FontStyle)
  • GetLineSpacing(FontStyle)

on the FontFamily class. And adjust the placement of the TextBlock.

Source: How to: Obtain Font Metrics

But i would really advice against doing so as there are characters that could be using the space like Á and j which have different heights and line placement.

You might have better default layouting experience with fonts that are monospaced like Consolas which for HELLO WORLD! prints pretty much to the middle of the border.

like image 159
Petr Vávro Avatar answered Nov 07 '22 02:11

Petr Vávro