android自定义view时获取文字宽高


Image

获取文字宽度:

1
2
3
4
5
private int getTextWidth(String text, Paint paint) {
Rect rect = new Rect();
paint.getTextBounds(text, 0, text.length(), rect);
return rect.width();
}

获取文字高度:

1
2
3
4
5
private int getTextHeight(String text, Paint paint) {
Rect rect = new Rect();
paint.getTextBounds(text, 0, text.length(), rect);
return rect.height();
}