问题
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