Wpf 獲取指定字體和大小的字符的長寬

Wpf 獲取指定字體和大小的字符的長寬

運行環境:Win10 x64, NetFrameWork 4.8, 做者:烏龍哈里,日期:2019-05-09
字體


參考:

章節:


好比一個 Consolas 字體,FontSize=15 的字符,到底有多寬多長,查了半天資料,終於想到一個笨方法,弄個單獨的 FormattedText ,而後得出長寬
this

using System.Globalization;
using System.Windows;
using System.Windows.Media;

namespace ATestWpf
{
    class Font
    {
        public (double width,double height) GetFontWidthHeight(Visual visual, double fontSize, string fontFamily)
        {
            var pixelsPerDip = VisualTreeHelper.GetDpi(visual).PixelsPerDip;
            FormattedText ft = new FormattedText(
                "E",
                CultureInfo.CurrentCulture,
                FlowDirection.LeftToRight,
                new Typeface(fontFamily),
                fontSize,
                Brushes.Black,
                pixelsPerDip
            );
            return (ft.Width,ft.Height);
        }
    }
}

調用:
spa

namespace ATestWpf
{
    /// <summary>
    /// MainWindow.xaml 的交互邏輯
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Font f = new Font();
            string ff = "consolas";
            double fs = 15;
            var t = f.GetFontWidthHeight(this,fs,ff);

            txtOutput.Text = $"fontfamily:{ff}\r\nfontsize:{fs}\r\nwidth:{t.width} \r\nheight:{t.height}";
            
            /*fontfamily:consolas
             *fontsize:15
             *width:8.24666666666667 
             *height:17.5633333333333
             */

        }

    }
}
相關文章
相關標籤/搜索