Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting height and width of a text using Canvas

I'm developing an Android 2.2 application.

I'm using this method to draw a text in a View:

    public void draw(Canvas c)
    {
        p.setColor(Color.WHITE);
        if(name != null)
            c.drawText(name, getLeft(), getTop(), p);
    }

How can I get height and width of name text?

If I do this (p is a Paint object):

p.getTextBounds(name, 0, name.length(), bounds);

I get With name = 'Loading', bounds = Rect(1, -10 - 42, 3);.

I don't know why I get this strange rectangle.

Any clue?

This is my possible solution:

public class MyView extends ARSphericalView
{
    public String name;

    public MyView(Context ctx)
    {
        super(ctx);
        inclination = 0;
    }

    public void draw(Canvas c)
    {
        /*
        p.setColor(Color.WHITE);
        if(name != null)
            c.drawText(name, getLeft(), getTop(), p);
        */
        p.setColor(Color.BLACK);
        if(name != null)
        {
            Rect bounds = new Rect();
            c.drawText(name, getLeft(), getTop(), p);
            setBackgroundColor(Color.WHITE);
            p.getTextBounds(name, 0, name.length(), bounds);
            c.drawRect(bounds, p);
        }
    }
}

But, it doesn't work. I get that strange rectangle.

like image 273
VansFannel Avatar asked Oct 10 '11 10:10

VansFannel


People also ask

How do I get text height in canvas?

To find the height of text on an HTML canvas with JavaScript, we can use the canvas context's measureText method. const metrics = ctx. measureText(text); const fontHeight = metrics.

How do you find the height and width of a canvas?

You can get the width and height of a canvas element simply by accessing those properties of the element. For example: var canvas = document. getElementById('mycanvas'); var width = canvas.

How do you find the width of text?

The dimensions of the text are calculated using the measureText() method. The text to be measured is passed to this method. It returns a TextMetrics object that contains information about the measured text. The width property of this TextMetrics object is used to get the width of the text.


1 Answers

A text size is measured from its baseline, and has an ascent (upwards, so -y) and descent (downwards, y). The first y-value in your rect (-10) is the ascent, the second the descent (3). Width of the text is 41 (42-1). Height thus is |ascent| + |descent| is 10 + 3 = 13;

Similarly p.getFontMetrics() has top and bottom attributes, which describe the highest ascent and descent the font you are using have. If you want to calculate the height of a text, then its Math.abs(p.ascent) + Math.abs(p.descent) You can also measure the width of a text with p.measureText().

like image 54
MrJre Avatar answered Oct 06 '22 04:10

MrJre