Android draw text into rectangle on center and crop it if needed

zmeda picture zmeda · Apr 1, 2011 · Viewed 14.3k times · Source

I want to draw text into rectangle on center (horizontally and vertically). If there is too much of a text that crop it what do not fit into rect.

I have try to do it as this example show, but without luck.

Any ideas?

Answer

Dandroid picture Dandroid · Mar 18, 2013

Try this

private void drawRectText(String text, Canvas canvas, Rect r) {

    textPaint.setTextSize(20);
    textPaint.setTextAlign(Align.CENTER);
    int width = r.width();

    int numOfChars = textPaint.breakText(text,true,width,null);
    int start = (text.length()-numOfChars)/2;
    canvas.drawText(text,start,start+numOfChars,r.exactCenterX(),r.exactCenterY(),textPaint);
}