c# 计算空格宽度像素_C#正确获取像素中的字符串宽度

Hi everyone,

I'm developing new software for me. But I have a little problem. When I wanna get the String Width, already I use that code;

float aa = pe.Graphics.MeasureString("PROGRAMMING", Font).Width;

But this value is not correct. When I test that line with that code;

pe.Graphics.DrawString("PROGRAMMING", Font, Brushes.White, new PointF(0, 0));

float aa = pe.Graphics.MeasureString("PROGRAMMING", Font).Width;

pe.Graphics.DrawLine(new Pen(Brushes.CadetBlue, 4), new PointF(0, 1), new PointF(aa, 1));

Result of this code;

https://social.msdn.microsoft.com/Forums/getfile/573128[^]

The Line length always going wrong.

How can I solve this problem? That's calculate very important for my project. I'm waiting for your helps. Thanks for all answer. Have a good day...

解决方案Using the default 'MeasureString and 'DrawString: leading-space and trailing-space may be automatically added when the string is rendered:"The MeasureString method is designed for use with individual strings and includes a small amount of extra space before and after the string to allow for overhanging glyphs. Also, the DrawString method adjusts glyph points to optimize display quality and might display a string narrower than reported by MeasureString." MSDNUse one of the StringFormat optional arguments as shown in the code here to block that default behavior.Font font = new System.Drawing.Font("Arial", 16.2F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

private void panel1_Paint(object sender, PaintEventArgs e)

{

Graphics pe = e.Graphics;

float aa = pe.MeasureString("PROGRAMMING", font,0,StringFormat.GenericTypographic).Width + 40;

pe.DrawString("PROGRAMMING", font, Brushes.White, new PointF(40, 40), StringFormat.GenericTypographic);

pe.DrawLine(new Pen(Brushes.CadetBlue, 4), new PointF(40, 40), new PointF(aa, 40));

}

try with TextRenderer.MeasureText Method[^]

sample code :

String text1 = "Measure this text";

Font arialBold = new Font("Arial", 12.0F);

Size textSize = TextRenderer.MeasureText(text1, arialBold);

TextRenderer.DrawText(e.Graphics, text1, arialBold,

new Rectangle(new Point(10, 10), textSize), Color.Red);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值