zoukankan      html  css  js  c++  java
  • c# 获得文字的像素宽度

    Graphics graphics = CreateGraphics();  
    SizeF sizeF = graphics.MeasureString(textBox1.Text, new Font("宋体", 9));
    MessageBox.Show(string.Format("字体宽度:{0},高度:{1}", sizeF.Width, sizeF.Height));
    graphics.Dispose();

      使用g.MeasureString()获得

    使用MeasureString测量出来的字符宽度,总是比实际宽度大一些,而且随着字符的长度增大,貌似实际宽度和测量宽度的差距也越来越大了。查了一下MSDN,找到了下面这个理由:

    MeasureString 方法旨在与个别字符串一起使用,它在字符串前后包括少量额外的空格供突出的标志符号使用。

                string str;
                str = "大";
                Font f = new Font("SimSun", 7F, System.Drawing.FontStyle.Regular);
                Graphics g = this.CreateGraphics();
                //单位为mm
                g.PageUnit = GraphicsUnit.Millimeter;
                SizeF sim = g.MeasureString(str, f);

    2、使用TextRenderer.MeasureText获得,提供使用指定尺寸创建文本初始边框时,使用指定的设备上下文、字体和格式说明所绘制的指定文本的尺寸(以像素为单位)。

            private void MeasureText(PaintEventArgs e) 
            {
                string str;
                str = "大家好";
                Font f = new Font("SimSun", 7F, System.Drawing.FontStyle.Regular);
                Size sif = TextRenderer.MeasureText(e.Graphics, str, f, new Size(0, 0), TextFormatFlags.NoPadding);
                MessageBox.Show((sif.Width / pdi).ToString());
            }

            private void print(object sender, PaintEventArgs e)
            {
                MeasureText(e);
            }

  • 相关阅读:
    token是什么?和session什么区别,怎么用
    HashTable详解
    Cookie和Session的区别
    测试基础面试题
    什么是回归测试?回归测试的主要目的是什么?
    每天一个linux常用命令--ls 和 -ll 有什么区别?
    python中6个序列的内置类型分别是什么,列表和元组的异同有哪些
    今天去面试自动化测试,被几个问题问住了,记录下
    python排序算法-冒泡和快速排序,解答阿里面试题
    Myeclipse使用积累
  • 原文地址:https://www.cnblogs.com/swtool/p/5425169.html
Copyright © 2011-2022 走看看