Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 263
Daniel L. Avatar asked Feb 28 '13 09:02

Daniel L.


2 Answers

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.
like image 164
Daniel L. Avatar answered Oct 17 '22 07:10

Daniel L.


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.

like image 33
Android2390 Avatar answered Oct 17 '22 06:10

Android2390