1. 程式人生 > >WPF中的文字度量

WPF中的文字度量

關於WPF中的文字度量,需要了解以下幾個問題:

  1. WPF中支援一些常用的度量單位:px(device independent pixels)、in(inches)、cm(centimeters)、pt(points)
  2. 預設的單位是px,當然也可以通過加單位來強制使用該單位。比如:

裝置無關畫素和物理畫素:

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

預設情況下,系統DPI為96,此時裝置無關畫素與物理畫素一致。
當系統DPI不是96時:

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

但系統DPI變大的時候,以裝置無關畫素為單位的元素也會變大。

Points

 1pt = 1/72 inches

所以,Points 與裝置無關畫素的關係如下:

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

由於系統DPI變大時,裝置無關畫素為單位的元素會變大。而Points與裝置無關畫素之間的比值保持不變,所以以Points為單位的元素也會變大。

怎麼測量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;
}

參考連結:
https://blogs.msdn.microsoft.com/text/2009/12/11/wpf-text-measurement-uni