Measuring text height to be drawn on Canvas ( Android )

112,925

Solution 1

What about paint.getTextBounds() (object method)

Solution 2

There are different ways to measure the height depending on what you need.

#1 getTextBounds

If you are doing something like precisely centering a small amount of fixed text, you probably want getTextBounds. You can get the bounding rectangle like this

Rect bounds = new Rect();
mTextPaint.getTextBounds(mText, 0, mText.length(), bounds);
int height = bounds.height();

As you can see for the following images, different strings will give different heights (shown in red).

enter image description here

These differing heights could be a disadvantage in some situations when you just need a constant height no matter what the text is. See the next section.

#2 Paint.FontMetrics

You can calculate the hight of the font from the font metrics. The height is always the same because it is obtained from the font, not any particular text string.

Paint.FontMetrics fm = mTextPaint.getFontMetrics();
float height = fm.descent - fm.ascent;

The baseline is the line that the text sits on. The descent is generally the furthest a character will go below the line and the ascent is generally the furthest a character will go above the line. To get the height you have to subtract ascent because it is a negative value. (The baseline is y=0 and y descreases up the screen.)

Look at the following image. The heights for both of the strings are 234.375.

enter image description here

If you want the line height rather than just the text height, you could do the following:

float height = fm.bottom - fm.top + fm.leading; // 265.4297

These are the bottom and top of the line. The leading (interline spacing) is usually zero, but you should add it anyway.

The images above come from this project. You can play around with it to see how Font Metrics work.

#3 StaticLayout

For measuring the height of multi-line text you should use a StaticLayout. I talked about it in some detail in this answer, but the basic way to get this height is like this:

String text = "This is some text. This is some text. This is some text. This is some text. This is some text. This is some text.";

TextPaint myTextPaint = new TextPaint();
myTextPaint.setAntiAlias(true);
myTextPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
myTextPaint.setColor(0xFF000000);

int width = 200;
Layout.Alignment alignment = Layout.Alignment.ALIGN_NORMAL;
float spacingMultiplier = 1;
float spacingAddition = 0;
boolean includePadding = false;

StaticLayout myStaticLayout = new StaticLayout(text, myTextPaint, width, alignment, spacingMultiplier, spacingAddition, includePadding);

float height = myStaticLayout.getHeight(); 

Solution 3

@bramp's answer is correct - partially, in that it does not mention that the calculated boundaries will be the minimum rectangle that contains the text fully with implicit start coordinates of 0, 0.

This means, that the height of, for example "Py" will be different from the height of "py" or "hi" or "oi" or "aw" because pixel-wise they require different heights.

This by no means is an equivalent to FontMetrics in classic java.

While width of a text is not much of a pain, height is.

In particular, if you need to vertically center-align the drawn text, try getting the boundaries of the text "a" (without quotes), instead of using the text you intend to draw. Works for me...

Here's what I mean:

Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.LINEAR_TEXT_FLAG);

paint.setStyle(Paint.Style.FILL);
paint.setColor(color);
paint.setTextAlign(Paint.Align.CENTER);
paint.setTextSize(textSize);

Rect bounds = new Rect();
paint.getTextBounds("a", 0, 1, bounds);

buffer.drawText(this.myText, canvasWidth >> 1, (canvasHeight + bounds.height()) >> 1, paint);
// remember x >> 1 is equivalent to x / 2, but works much much faster

Vertically center aligning the text means vertically center align the bounding rectangle - which is different for different texts (caps, long letters etc). But what we actually want to do is to also align the baselines of rendered texts, such that they did not appear elevated or grooved. So, as long as we know the center of the smallest letter ("a" for example) we then can reuse its alignment for the rest of the texts. This will center align all the texts as well as baseline-align them.

Solution 4

The height is the text size you have set on the Paint variable.

Another way to find out the height is

mPaint.getTextSize();

Solution 5

You could use the android.text.StaticLayout class to specify the bounds required and then call getHeight(). You can draw the text (contained in the layout) by calling its draw(Canvas) method.

Share:
112,925

Related videos on Youtube

Danedo
Author by

Danedo

Updated on November 14, 2020

Comments

  • Danedo
    Danedo over 3 years

    Any straight forward way to measure the height of text? The way I am doing it now is by using Paint's measureText() to get the width, then by trial and error finding a value to get an approximate height. I've also been messing around with FontMetrics, but all these seem like approximate methods that suck.

    I am trying to scale things for different resolutions. I can do it, but I end up with incredibly verbose code with lots of calculations to determine relative sizes. I hate it! There has to be a better way.

  • AgentKnopf
    AgentKnopf about 12 years
    This yields very odd results, when I evaluate the height of a text. A short text results in a height of 12, whereas a REALLY long text results in a height of 16 (given a font size of 16). Makes no sense to me (android 2.3.3)
  • Nar Gar
    Nar Gar over 11 years
    Not if you're dealing with multiple segments of texts. The reason is in my answer above.
  • FrinkTheBrave
    FrinkTheBrave over 11 years
    The variance in height is where you have descenders in the text, i.e. 'High' is taller than 'Low' because of the part of the g below the line
  • keaukraine
    keaukraine over 11 years
    Haven't seen x >> 1 for ages. Upvoting only for that :)
  • intrepidis
    intrepidis about 11 years
    A good modern compiler will see x / 2 and optimize it to x >> 1
  • d3dave
    d3dave over 10 years
    @keaukraine x / 2 is much more friendly when reading code, considering Chris' comment.
  • Erigami
    Erigami about 9 years
    Where does the 24.0f come from?
  • moondroid
    moondroid about 9 years
    24.0f it's just an example for a text size
  • zoltish
    zoltish over 8 years
    -1 for allocations in onDraw(): It would yield a ton of performance benefits if you were to declare the fields in the class (initiate in constructor) and re-use them in onDraw().
  • Micheal Johnson
    Micheal Johnson about 7 years
    Nice explanation. What app are the screenshots from?
  • Suragch
    Suragch about 7 years
    @MichealJohnson, I added the app as a GitHub project here.
  • AutonomousApps
    AutonomousApps about 6 years
    what is buffer in this example? Is it the canvas passed to the draw(Canvas) method?
  • android developer
    android developer almost 6 years
    What does "getTextSize" give you, then?
  • Suragch
    Suragch almost 6 years
    Paint's getTextSize() gives you the font size in pixel units (as opposed to sp units). @androiddeveloper
  • Suragch
    Suragch almost 6 years
    What is the relationship of the font size in pixel units to the measured height and to the FontMetrics dimensions? That is a question that I would like to explore more.
  • Chisko
    Chisko almost 6 years
    @AutonomousApps yes, it's the canvas
  • TheRealChx101
    TheRealChx101 over 5 years
    Let's vote this to the top. It's comprehensive and shows alternatives.
  • Jim Leask
    Jim Leask over 5 years
    How can you do this in reverse? I have a view of height, say 50dp, and I want to set the text size to match this height so it fills the box.
  • Suragch
    Suragch over 5 years
    @JimLeask, You can use Autosizing TextViews. But if you are drawing text on canvas yourself then you have to set the font, measure it, reset the font, measure it...until you have the desired height.
  • Jim Leask
    Jim Leask over 5 years
    @Suragch I am drawing directly to the canvas. It is surprising that there isn't an API to get the font for a given height. Finding the font size by trail and error with iterating through values is not a great solution, but it seems that is a missing API in Android so all I can do.
  • Suragch
    Suragch over 5 years
    @JimLeask, I think the reason there is no API is because the actual height at a certain font size is up to the font developer and there is no standard for what it must be. That is, there is no definite correlation between font size and text height. If you go the trial and error route, you could do a binary search. That is what TextView does under the hood. A new idea I saw recently is to convert the text to a path. I think if you had a path you could set the size more directly. I haven't tried it yet, though.
  • RonTLV
    RonTLV over 5 years
    When using FontMetrics, is it sp, dp, or pixels ?
  • Suragch
    Suragch over 5 years
    @RonTLV, with FontMetrics it is pixels. When you get into lower level graphics rendering like this it is all pixels. In the StaticLayout example above I made the dp conversion by multiplying by the device density. See this Q&A also.
  • Ωmega
    Ωmega almost 5 years
    @Suragch - please advise how to calculate text height for styles, such as @style/TextAppearance.AppCompat.Notification.Title. Thank you!
  • Suragch
    Suragch almost 5 years
    @Ωmega, I'm not sure off hand, but see if you can get a reference to the TextPaint or FontMetrics from whatever object you are working with.
  • Top-Master
    Top-Master almost 2 years
    If you don't want variances, use Paint.FontMetrics instead.