Search code examples
androidandroid-canvasandroid-custom-view

How Canvas.drawText() really draws the text?


In this method documentation it's written that:

x   The x-coordinate of origin for where to draw the text
y   The y-coordinate of origin for where to draw the text

But it doesn't say anything about the direction this text is drawn. I know that the text is drawn from the origin up, but when I give the following arguments, my text gets cut:

canvas.drawText(displayText, 0, canvas.getHeight(), textPaint);

in addition, assume I'm using Align.LEFT (meaning that the text is drawn to the right of the x,y origin)

So what are the correct arguments should be (assuming I don't want to use fixed numbers)?


Solution

  • This is what I eventually used:

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (textAlignment == Align.CENTER) {
            canvas.drawText(displayText, canvas.getWidth()/2, canvas.getHeight()-TEXT_PADDING, textPaint);  
        }
        else if (textAlignment == Align.RIGHT) {
            canvas.drawText(displayText, canvas.getWidth()-TEXT_PADDING, canvas.getHeight()-TEXT_PADDING, textPaint);   
        }
        else if (textAlignment == Align.LEFT) {
            canvas.drawText(displayText, TEXT_PADDING, canvas.getHeight()-TEXT_PADDING, textPaint); 
        }   
        //canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), p);
    }
    

    Two comments:

    1. TEXT_PADDING is a dp dimension I convert to pixels at runtime (in my case 3dp).
    2. You can un-comment the the last line to draw the rect around your canvas for debug.