Wpf 获取指定字体和大小的字符的长宽

Wpf 获取指定字体和大小的字符的长宽

运行环境:Win10 x64, NetFrameWork 4.8, 作者:乌龙哈里,日期:2019-05-09


参考:

章节:


比如一个 Consolas 字体,FontSize=15 的字符,到底有多宽多长,查了半天资料,终于想到一个笨方法,弄个单独的 FormattedText ,然后得出长宽

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);
        }
    }
}

调用:

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

        }

    }
}

猜你喜欢

转载自www.cnblogs.com/leemano/p/10841436.html
WPF