开发者

Determining string/font dimensions

I have a method that is passed a text string. For a specified font and size, it works out the bounding box for the text and then draws a roundrect that will contain it.

I'm trying to keep all of these roundrects the same hei开发者_JAVA技巧ght (irrespective of ascenders and descenders in the font), so the basic getTextBounds isn't quite enough as it bounds the specific text passed.

The solution I came up with was to use getTextBounds to work out the width of the text, and ascent/descent from FontMetricsInt to work out the height:

Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setTextSize(fontsize);
paint.setTypeface(Typeface.SANS_SERIF);
Rect textBounds = new Rect();
paint.getTextBounds(value, 0, value.length(), textBounds);
FontMetricsInt fm = paint.getFontMetricsInt();
this.width = textBounds.width();
this.height = fm.descent - fm.ascent;
this.textAscent = fm.ascent;

Is there a simpler way?

Edits: Finally figured out how to format the code properly!


Why don't you use use direct function like: paint.measureText(value), paint.ascent(), paint.descent()? The code would be:

Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setTextSize(fontsize);
paint.setTypeface(Typeface.SANS_SERIF);
this.width = paint.measureText(value);
this.height = paint.descent() - paint.ascent();
this.textAscent = paint.ascent();

Not a big improvement, but easier to read.


You don't need to subtract ascent() from descent(). You can just use Paint.getFontSpacing() :

Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setTextSize(fontsize);
paint.setTypeface(Typeface.SANS_SERIF);
this.width = paint.measureText(value);
this.height = paint.getFontSpacing();
this.textAscent = paint.ascent();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜