Android and calculating the size of a one-line string in a given font and font size?

耗尽温柔 提交于 2019-12-05 23:19:13

问题


Is there an API method for calculating the size (i.e. width and height) of a string displayed on one line and in a given font and font size?


回答1:


Paint p = new Paint();
p.setTypeface(TypeFace obj); // if custom font use `TypeFace.createFromFile`
p.setTextSize(float size);
float textWidth = p.measureText("Your string"); 
// you get the width here and textsize is the height.



回答2:


Paint mPaint = new Paint();
mPaint.setTextSize(/*put here ur size*/);
mPaint.setTypeface(/* put here ur font type */);
Rect bounds = new Rect();
mPaint.getTextBounds(text, 0, text.length(), bounds);

then make the call of

bounds.width();

bounds.height();



回答3:


The Paint class has a method measureText() which will give you the width in float

Paint p = new Paint();
int INFO_WINDOW_WIDTH = (int)p.measureText("this is string");

and another is Paint.getTextBounds



来源:https://stackoverflow.com/questions/7329004/android-and-calculating-the-size-of-a-one-line-string-in-a-given-font-and-font-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!