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.
@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:
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.
You could use the
android.text.StaticLayout
class to specify the bounds required and then callgetHeight()
. You can draw the text (contained in the layout) by calling itsdraw(Canvas)
method.The height is the text size you have set on the Paint variable.
Another way to find out the height is
What about paint.getTextBounds() (object method)
You can simply get the text size for a Paint object using getTextSize() method. For example:
If anyone still has problem, this is my code.
I have a custom view which is square (width = height) and I want to assign a character to it.
onDraw()
shows how to get height of character, although I'm not using it. Character will be displayed in the middle of view.