How to align text vertically?
Example to centre on cx
and cy
:
private final Rect textBounds = new Rect(); //don't new this up in a draw methodpublic void drawTextCentred(Canvas canvas, Paint paint, String text, float cx, float cy){ paint.getTextBounds(text, 0, text.length(), textBounds); canvas.drawText(text, cx - textBounds.exactCenterX(), cy - textBounds.exactCenterY(), paint);}
Why doesn't height()/2f
work the same?
exactCentre()
= (top + bottom) / 2f
.
height()/2f
= (bottom - top) / 2f
These would only yield the same result when top
is 0
. This may be the case for some fonts at all sizes, or other fonts at some sizes, but not for all fonts at all sizes.
Based on steelbytes' response, the updated code would look something like:
void drawHelloRectangle(Canvas c, int topLeftX, int topLeftY, int width, int height) { Paint mPaint = new Paint(); // height of 'Hello World'; height*0.7 looks good int fontHeight = (int)(height*0.7); mPaint.setColor(COLOR_RED); mPaint.setStyle(Style.FILL); c.drawRect( topLeftX, topLeftY, topLeftX+width, topLeftY+height, mPaint); mPaint.setTextSize(fontHeight); mPaint.setColor(COLOR_BLACK); mPaint.setTextAlign(Align.CENTER); String textToDraw = new String("Hello World"); Rect bounds = new Rect(); mPaint.getTextBounds(textToDraw, 0, textToDraw.length(), bounds); c.drawText(textToDraw, topLeftX+width/2, topLeftY+height/2+(bounds.bottom-bounds.top)/2, mPaint);}