I have a rectangle that I want to draw text inside. I want the text to be centered vertically and horizontally and I need the text size to changed to fit all characters inside the rectangle. Here is my code:
@Override
public void drawFixedText(String text, Rect rect, Paint paint) {
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.FILL);
int cX = rect.left;
int cY = rect.top;
float textSize = paint.getTextSize();
paint.setTextSize(textSize);
float textWidth = paint.measureText(text);
while (textWidth > rect.width()) {
textSize--;
paint.setTextSize(textSize);
}
//if cX and cY are the origin coordinates of the your rectangle
//cX-(textWidth/2) = The x-coordinate of the origin of the text being drawn
//cY+(textSize/2) = The y-coordinate of the origin of the text being drawn
canvas.drawText(text, cX-(textWidth/2), cY+(textSize/2), paint);
}
I tried to combine the answers from Calculate text size according to width of text area and Android draw text into rectangle on center and crop it if needed
But it didn't work in that the text is placed to the left of the rectangle instead of inside of it. How can I fix this?