• 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}
    fontsize:{fs}
    {t.width} 
    height:{t.height}";
                
                /*fontfamily:consolas
                 *fontsize:15
                 *8.24666666666667 
                 *height:17.5633333333333
                 */
    
            }
    
        }
    }
  • 相关阅读:
    web.xml配置文件
    数组去重问题
    Mysql优化
    点赞功能
    IDEA的一些使用小技巧
    Maven
    AJAX
    HTTP响应头拆分/CRLF注入详解
    对寄存器ESP和EBP的一些理解
    汇编调用指令的执行过程
  • 原文地址:https://www.cnblogs.com/leemano/p/10841436.html
Copyright © 2020-2023  润新知