1

I am trying to draw a text at the centre of canvas, Since canvas starts drawing text at BaseLine, I am not able to Place it at centre. If i can get the baseLine, then i can calculate the centre.

I have tried with paint.getFontMetrics() this gives ascent and descent but not baseLine.

2 Answers2

3

Did you try this code

private void drawCenter(Canvas canvas, Paint paint, String text) {
    canvas.getClipBounds(r);
    int cHeight = r.height();
    int cWidth = r.width();
    paint.setTextAlign(Paint.Align.LEFT);
    paint.getTextBounds(text, 0, text.length(), r);
    float x = cWidth / 2f - r.width() / 2f - r.left;
    float y = cHeight / 2f + r.height() / 2f - r.bottom;
    canvas.drawText(text, x, y, paint);
}
Jahanvi Kariya
  • 377
  • 3
  • 14
0

All the calculations of paint.getFontMetrics() will happen with respect to baseLine. So if i just subtract (getMeasuredHeight() / 2f) - (fontMetrics.ascent / 2f) it will draw from center