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

  • 相关阅读:
    心情日记:【原创诗歌】怆情吟
    心情日记:2008年3月3日 奶奶去世
    心情日记:健身日记
    金融基础概念期货
    FXDD点值获利计算
    外汇基础概念汇率
    报告论文:是学生都copy下来,现在不用,将来绝对要用(转)
    情感日记:毕业临走物语
    美元为什么坚挺
    英特尔首席技术官:人机智能鸿沟将于2050年消失
  • 原文地址:https://www.cnblogs.com/swtool/p/5425169.html
Copyright © 2011-2022 走看看