I am creating a Custom View where I have to draw text at specific positions on the canvas. For using canvas.drawText() we have to create a paint object that has to be passed as a parameter while calling the drawText(). If I want to get the text to be rendered as centrally aligned, I am using the setTextAlign() call while making the paint object.
statPaint.setTextAlign(Paint.Align.CENTER);
Also when I call the drawText(), I am required to set the starting point for the text to be rendered, as shown below.
canvas.drawText(stat1,paddingLeft,paddingTop,statPaint);
paddingLeft and paddingTop tell the drawText() where to draw the text from. Passing these two parameters is mandatory for the function call. But I still am not able to get the text centrally aligned. How do I get this text centrally aligned.
Also if I want to get two different texts in the same line, the first one being centrally aligned in the first half of the screen, and the second text, centrally aligned in the second half of the screen, how do I do that? The screen is divided into halves vertically.
Thanks in advance.
Here is how to center text in any rectangle (just change left/right/top/bottom)
// Allocated once as a member var, not in each onDraw
private Rect rect = new Rect();
// Inside onDraw
int left = 0;
int right = getWidth();
int top = 0;
int bottom = getHeight();
paint.getTextBounds(text, 0, text.length(), rect);
FontMetrics fm = paint.getFontMetrics();
float x = left + (right - left - rect.width()) / 2;
float y = top + (bottom - top) / 2 - (fm.descent + fm.ascent) / 2;
canvas.drawText(text, x, y, paint);