How Canvas.drawText () really draws text?

This documentation method says 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 he says nothing about the direction this text is drawn. I know that the text is pulled up from the source, but when I give the following arguments, my text is truncated:

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

Also, suppose I use Align.LEFT (this means that the text is drawn to the right of the beginning of x, y)

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

+6
source share
2 answers

This is what I ended up using:

 @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:

  • TEXT_PADDING is a dp dimension that I convert to pixels at runtime (in my case 3dp).
  • You can undo the comment of the last line to draw a rectangle around your canvas for debugging.
+2
source

Perhaps you can use the following snippet to find out if it works or not:

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

Width and height are computed arbitrarily in my case.

+2
source

All Articles