Daniel L.
Daniel L.

Reputation: 5140

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)?

Upvotes: 8

Views: 12223

Answers (2)

Daniel L.
Daniel L.

Reputation: 5140

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.

Upvotes: 5

Android2390
Android2390

Reputation: 1150

Maybe you can use the following snippet to see if its working or not :

int width = this.getMeasuredWidth()/2;
int height = this.getMeasuredHeight()/2;
textPaint.setTextAlign(Align.LEFT);
canvas.drawText(displayText, width, height, textPaint);

The width and height are just calculated arbitrarily in my case.

Upvotes: 1

Related Questions