137

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?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
NioX5199
  • 1,772
  • 4
  • 13
  • 12

8 Answers8

252

Have you looked at android.graphics.Paint#measureText(String txt)?

Mahozad
  • 18,032
  • 13
  • 118
  • 133
Marc Bernstein
  • 11,423
  • 5
  • 34
  • 32
  • 21
    Thanks this is it! I don't know why I skipped it. The purpose was to simply draw a text at the center of the screen. Anyway I just realized I could also have just used setTextAlign(Align.CENTER) on the Paint used to draw the text, it shifts the specified origin to the center of the drawn text. Thanks. – NioX5199 Jul 15 '10 at 16:17
  • 3
    Great, thanks, setting Align on the Paint! who would have thought of that...? – Sanjay Manohar Aug 05 '11 at 02:22
  • or you can set the Gravity of the textview to Center – yeradis Oct 21 '11 at 14:38
38
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();
Paresh J
  • 2,401
  • 3
  • 24
  • 31
19

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

Community
  • 1
  • 1
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
7

There's actually three different ways of measuring text.

GetTextBounds:

val paint = Paint()
paint.typeface = ResourcesCompat.getFont(context, R.font.kaushanscript)
paint.textSize = 500f
paint.color = Color.argb(255, 3, 221, 252)
val contents = "g"
val rect = Rect()
paint.getTextBounds(contents, 0, 1, rect)
val width = rect.width()

MeasureTextWidth:

val paint = Paint()
paint.typeface = ResourcesCompat.getFont(context, R.font.kaushanscript)
paint.textSize = 500f
paint.color = Color.argb(255, 3, 221, 252)
val contents = "g"
val width = paint.measureText(contents, 0, 1)

And getTextWidths:

val paint = Paint()
paint.typeface = ResourcesCompat.getFont(context, R.font.kaushanscript)
paint.textSize = 500f
paint.color = Color.argb(255, 3, 221, 252)
val contents = "g"
val rect = Rect()
val arry = FloatArray(contents.length)
paint.getTextBounds(contents, 0, contents.length, rect)
paint.getTextWidths(contents, 0, contents.length, arry)
val width = ary.sum()

Note that getTextWidths could be useful if you are trying to determine when to wrap text to the next line.

The measureTextWidth and getTextWidth are equal and have the advanced width that measure that others have posted about. Some consider this space excessive. However, this is very subjective and dependent on the font.

For example the width from measure text bounds may actually look too small:

measure text bounds looks small

However when adding an additional text the bounds for one letter looks normal: measure text bounds looks normal for strings

Images taken from Android Developers Guide to Custom Canvas Drawing

Jim Baca
  • 6,112
  • 2
  • 24
  • 30
1

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.

Hiren Patel
  • 52,124
  • 21
  • 173
  • 151
0

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.

Armin J.
  • 435
  • 1
  • 4
  • 10
  • Because kerning (space between letters) is dependent on individual letter sequences this will probably only work satisfactorily with fixed with fonts like Courier. – Merk Jul 17 '21 at 18:07
0

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

Ashish John
  • 1,867
  • 2
  • 23
  • 38
0

This should work.

fun String.getWidth(fontSize: Float): Float {
    val textPaint = TextPaint()
    textPaint.textSize = fontSize
    textPaint.typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)

    return textPaint.measureText(this)
}

Advance for text with new line break

fun String.getWidth(fontSize: Float): Float {
    val textPaint = TextPaint()
    textPaint.textSize = fontSize
    textPaint.typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
    val texts = this.split("\n")
    if (texts.size == 1) {
        return textPaint.measureText(this)
    }

    var finalWidth = 0f
    for (text in texts) {
        val thisLineWidth = text.getWidth(fontSize)
        if (thisLineWidth > finalWidth) {
            finalWidth = thisLineWidth
        }
    }

    return finalWidth
}
Binh Ho
  • 3,690
  • 1
  • 31
  • 31