8

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

Daniel L.
  • 5,060
  • 10
  • 36
  • 59
  • maybe this is what you are looking for (check the comment on the answer). http://stackoverflow.com/questions/10606410/android-canvas-drawtext-y-position-of-text – Master Chief Feb 28 '13 at 09:52
  • how does the text get cut? Is any text even showing? – Barney Feb 28 '13 at 10:01
  • If you trying setting the y value to canvas.getHeight() / 2, does it correctly show the text appearing in the middle? Also, you should say what you want to accomplish more concretely. – Barney Feb 28 '13 at 10:03
  • getHeight/2 results in the text being cut as well, this time the upper part of the text is cut and not the bottom part of it as in the original situation. – Daniel L. Feb 28 '13 at 10:09

2 Answers2

5

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.
Daniel L.
  • 5,060
  • 10
  • 36
  • 59
1

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.

Blumer
  • 5,005
  • 2
  • 33
  • 47
Android2390
  • 1,150
  • 12
  • 21