Measuring text width to be drawn on Canvas ( Andro

2019-01-21 06:10发布

Is there a method which returns the width ( in pixels ) of a text to be drawn on an Android canvas using the drawText() method according to the Paint used to draw it?

6条回答
forever°为你锁心
2楼-- · 2019-01-21 06:35

you can use "textPaint.getTextSize()" to get text width

查看更多
Summer. ? 凉城
3楼-- · 2019-01-21 06:43
Paint paint = new Paint();
Rect bounds = new Rect();

int text_height = 0;
int text_width = 0;

paint.setTypeface(Typeface.DEFAULT);// your preference here
paint.setTextSize(25);// have this the same as your text size

String text = "Some random text";

paint.getTextBounds(text, 0, text.length(), bounds);

text_height =  bounds.height();
text_width =  bounds.width();
查看更多
三岁会撩人
4楼-- · 2019-01-21 06:43

Well I have done in different way:

String finalVal ="Hiren Patel";

Paint paint = new Paint();
paint.setTextSize(40);
Typeface typeface = Typeface.createFromAsset(getAssets(), "Helvetica.ttf");
paint.setTypeface(typeface);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL);

Rect result = new Rect();
paint.getTextBounds(finalVal, 0, finalVal.length(), result);

Log.i("Text dimensions", "Width: "+result.width()+"-Height: "+result.height());

Hope this will help you.

查看更多
干净又极端
5楼-- · 2019-01-21 06:44

Supplemental answer

There is a slight difference between the width returned by Paint.measureText and Paint.getTextBounds. measureText returns a width that includes the glyph's advanceX value padding the beginning and end of the string. The Rect width returned by getTextBounds does not have this padding because the bounds is the Rect that tightly wraps the text.

source

查看更多
疯言疯语
7楼-- · 2019-01-21 06:55

I used the methods measureText() and getTextPath()+computeBounds() and build up an Excel with all text attributes for fixed size font that can be found under https://github.com/ArminJo/android-blue-display/blob/master/TextWidth.xlsx . There you will find also simple formulas for other text attributes like ascend etc.

The app as well as the function drawFontTest() for generating the raw values used in the excel are also available in this repo.

查看更多
登录 后发表回答