首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Android上获取字符串宽度?

如何在Android上获取字符串宽度?
EN

Stack Overflow用户
提问于 2010-09-03 02:35:47
回答 4查看 75.6K关注 0票数 110

如果可能的话,我也想要身高。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2010-09-03 03:05:40

可以使用Paint对象的getTextBounds(String text, int start, int end, Rect bounds)方法。您可以使用TextView提供的paint对象,也可以自己构建具有所需文本外观的paint对象。

使用Textview,您可以执行以下操作:

代码语言:javascript
复制
Rect bounds = new Rect();
Paint textPaint = textView.getPaint();
textPaint.getTextBounds(text, 0, text.length(), bounds);
int height = bounds.height();
int width = bounds.width();
票数 213
EN

Stack Overflow用户

发布于 2012-06-17 08:55:57

如果你只需要宽度,你可以使用:

代码语言:javascript
复制
float width = paint.measureText(string);

http://developer.android.com/reference/android/graphics/Paint.html#measureText(java.lang.String)

票数 85
EN

Stack Overflow用户

发布于 2016-12-09 19:07:15

我用这种方法测量过宽度:

代码语言:javascript
复制
String str ="Hiren Patel";

Paint paint = new Paint();
paint.setTextSize(20);
Typeface typeface = Typeface.createFromAsset(getAssets(), "Helvetica.ttf");
paint.setTypeface(typeface);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL);
Rect result = new Rect();
paint.getTextBounds(str, 0, str.length(), result);

Log.i("Text dimensions", "Width: "+result.width());

这会对你有帮助。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3630086

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档