ik024
ik024

Reputation: 3596

Center text in Canvas Android

I would like to center my text (tp-TextPaint) in the rectangle speech bubble figure that I have drawn on the canvas. Does any one have any idea? I have achieved it using canvas.drawText() but I want to get it using staticLayout so that the text resizes when I resize the canvas width and height. Below is my code.

@Override
protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub
    super.onDraw(canvas);
    drawPath.reset();

    drawPath.moveTo(0, 0);
    drawPath.lineTo(getWidth(), 0);
    drawPath.lineTo(getWidth(), 100);
    drawPath.lineTo((getWidth()/2) +20, 100);
    drawPath.lineTo(getWidth()/2, 140);
    drawPath.lineTo((getWidth()/2)-20, 100);
    drawPath.lineTo(0, 100);
    drawPath.lineTo(0, 0);

    canvas.drawPath(drawPath, drawPaint);

    TextPaint tp = new TextPaint();
    tp.setColor(Color.BLACK);
    tp.setTextSize(25);
    tp.setAntiAlias(true);


    StaticLayout sl = new StaticLayout("" + s, tp, getWidth(),Alignment.ALIGN_CENTER, 1.0f, 0.0f, true);
     sl.draw(canvas);

     }

Upvotes: 2

Views: 10402

Answers (2)

Gopal Gopi
Gopal Gopi

Reputation: 11131

this may help you...

public static void drawText(Canvas canvas, Paint paint, String text) {
    Rect bounds = new Rect();
    paint.getTextBounds(text, 0, text.length(), bounds);
    int x = (canvas.getWidth() / 2) - (bounds.width() / 2);
    int y = (canvas.getHeight() / 2) - (bounds.height() / 2);
    canvas.drawText(text, x, y, paint);
}

Upvotes: 14

Kostya  Khuta
Kostya Khuta

Reputation: 683

Try it:

int xPos = (canvas.getWidth() / 2);
int yPos = (int) ((canvas.getHeight() / 2) - ((textPaint.descent() + textPaint.ascent()) / 2)) ; 
//((textPaint.descent() + textPaint.ascent()) / 2) is the distance from the baseline to the center.
canvas.drawText("Hello", xPos, yPos, textPaint);

Upvotes: 2

Related Questions