13

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?

zmeda
  • 2,843
  • 8
  • 34
  • 56
  • Check this, it is some what same as what you need, http://stackoverflow.com/questions/13285510/how-to-overlay-image-with-multiline-texttext-will-be-in-center-of-the-canvas/13287621#13287621 – Abhishek Nandi Mar 18 '13 at 13:57
  • Try this, it's work for me: http://stackoverflow.com/questions/11120392/android-center-text-on-canvas – fabio.cappelli.spot Feb 22 '17 at 15:37
  • This work for me, try it. [http://stackoverflow.com/questions/11120392/android-center-text-on-canvas](http://stackoverflow.com/questions/11120392/android-center-text-on-canvas) – fabio.cappelli.spot Feb 27 '17 at 08:23

2 Answers2

12

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);
}
Dandroid
  • 211
  • 2
  • 13
5

this function worked for me.

private void drawDigit(Canvas canvas, int textSize,  float cX, float cY, int color, String text) {
        Paint tempTextPaint = new Paint();
        tempTextPaint.setAntiAlias(true);
        tempTextPaint.setStyle(Paint.Style.FILL);

        tempTextPaint.setColor(color); 
        tempTextPaint.setTextSize(textSize); 

        float textWidth = tempTextPaint.measureText(text);
        //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), tempTextPaint);
    }
Mehmet Emre
  • 1,744
  • 20
  • 35