c# 自动计算字符串的宽度

本文详细介绍了如何使用TextRenderer.MeasureText方法来获取字符串的像素宽度,并通过实例对比了不同方法的差异,最终选择了较为准确的TextRenderer.MeasureText作为推荐方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

测试代码:

string str = "字符串";
var width = TextRenderer.MeasureText(str, this.Font);
var width2 = this.CreateGraphics().MeasureString(str, this.Font);

str = "字符串"时,结果为:

width:{Width=41, Height=12}

width2:{Width=41.06836, Height=15.1875}

AutoSize = true的Label尺寸为41, 12

str = "zifuchuan"时,结果为:

width:{Width=59, Height=12}

width2:{Width=59.68748, Height=13.5}

AutoSize = true的Label尺寸为59, 12

综合上述的结果,我取用TextRenderer.MeasureText作为最终获取字符串像素宽度的方法。

转载于:https://www.cnblogs.com/icyJ/p/MeasureText.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值