Android并计算给定字体和字体大小的单行字符串的大小?

SK9*_*SK9 7 string size fonts android

是否有一种API方法来计算显示在一行上的字符串的大小(即宽度和高度)以及给定的字体和字体大小?

Ron*_*nie 9

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.
Run Code Online (Sandbox Code Playgroud)


con*_*ius 8

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);
Run Code Online (Sandbox Code Playgroud)

然后拨打电话

bounds.width();

bounds.height();
Run Code Online (Sandbox Code Playgroud)