Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 664
zmeda Avatar asked Apr 01 '11 11:04

zmeda


2 Answers

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);
}
like image 102
Dandroid Avatar answered Oct 22 '22 19:10

Dandroid


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);
    }
like image 5
Mehmet Emre Avatar answered Oct 22 '22 21:10

Mehmet Emre