Android 中如何得到字符的像素宽度。求各位大侠鼎力相助。

ashou706 2010-11-12 01:34:11
Android 中如何得到字符串的像素宽度。?
条件是:在不同字体,和不同大小的情况下都可以
求各位大侠鼎力相助。,万分感谢。
...全文
1229 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
lazy_2010 2010-11-20
  • 打赏
  • 举报
回复
某些字符的 rect.left > 0
ashou706 2010-11-15
  • 打赏
  • 举报
回复
Paint mPaint = new Paint();
mPaint.setTextSize(16);
float FontSpace = mPaint.getFontSpacing();
return text.length()*FontSpace;
最后的结果 用字符串长度 × 字体宽度。得到字符长度最接近实际长度,但是当出现英文或者是标点符号时,长度就会缩小
牛叔 2010-11-12
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 ashou706 的回复:]

mTextPaint.measureText(displayText);
大家都倾向于上面的方法,但是我测试的时候为什么会比实际小呢,大家测了没有
[/Quote]
private final Paint pFont = new Paint();
Rect rect = new Rect();
pFont.getTextBounds("小", 0, 1, rect);
Log.v(TAG, "height:"+rect.height()+"width:"+rect.width());

我用的是这个,比实际小,倒是没测。
但是我真的没有找到比这个更好的方法了。
那个getsize()肯定是不能用的,大小绝对不对。
ashou706 2010-11-12
  • 打赏
  • 举报
回复
mTextPaint.measureText(displayText);
大家都倾向于上面的方法,但是我测试的时候为什么会比实际小呢,大家测了没有
牛叔 2010-11-12
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 zhq56030207 的回复:]

字符串宽度可以这样:
Paint paint = new Paint();
float strWidth = paint.measureText(String);
paint.setTextSize(tv.getTextSize());
二.
private final Paint pFont = new Paint();
Rect rect = new Rect();
pFont……
[/Quote]

这个问题我也遇到过,就是用这个方法解决的
chenzhp 2010-11-12
  • 打赏
  • 举报
回复
Paint mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);    
mTextPaint.setColor(Color.WHITE);
// Define the string.
String displayText = “Hello World!”;
// Measure the width of the text string.
float textWidth = mTextPaint.measureText(displayText);


纠结的木棉花 2010-11-12
  • 打赏
  • 举报
回复
字符串宽度可以这样:
Paint paint = new Paint();
float strWidth = paint.measureText(String);
paint.setTextSize(tv.getTextSize());
二.
private final Paint pFont = new Paint();
Rect rect = new Rect();
pFont.getTextBounds("小", 0, 1, rect);
Log.v(TAG, "height:"+rect.height()+"width:"+rect.width());

80,337

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧