Text metrics in WPF

About text metrics WPF, you need to understand the following questions:

  1. WPF support in some common unit of measure: px (device independent pixels), in (inches), cm (centimeters), pt (points)
  2. The default units are px, of course, also be used to force the unit by adding the unit. such as:

Physical device independent pixel and the pixels:

1 deveice independent pixel = 1/96 inch
1 physical pixel = 1/DPI inch

By default, the system 96 DPI, this time regardless of the pixel is consistent with the physical device pixels.
When the system DPI than 96:

physical pixels = DPI/96 * device independent pixels
device independent pixels = 96/DPI * physical pixels

DPI but the system becomes large when pixels to device independent element also become large.

Points

 1pt = 1/72 inches

Therefore, the relationship between device-independent pixels Points are as follows:

1pt = 72/96 device independent pixels
device independent pixels = 96/72 pt

Since the DPI system becomes large, the device independent pixels elements becomes large. Points and the ratio between the device-independent pixels remain unchanged, in units of Points element also become large.

How to measure the width of TextBlock

private double GetDrawingWidth(string str, TextBlock textBlock)
{
    var formattedText = new FormattedText(
        str,
        CultureInfo.CurrentCulture,
        textBlock.FlowDirection,
        new Typeface(textBlock.FontFamily, textBlock.FontStyle, textBlock.FontWeight, textBlock.FontStretch),
        textBlock.FontSize,
        textBlock.Foreground,
        VisualTreeHelper.GetDpi(textBlock).PixelsPerDip);

    return formattedText.Width;
}

Reference Links:
https://blogs.msdn.microsoft.com/text/2009/12/11/wpf-text-measurement-units/

Guess you like

Origin www.cnblogs.com/frendguo/p/11755236.html