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

        }

    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM