2
votes

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);

     }
2
You want to center tp within the shape? First, the shape seems a bit irregular... Second, have you tried calling tp.getWidth() and tp.getHeight()? - Mike Ortiz
Which is the "rectangle figure"? - Amulya Khare
sorry i wasnt precise before I have edited my question - ik024
@Mike Ortiz how will tp.getWidth and tp.getHeight() help me center it? - ik024
With a little math, you can easily center the view if you know the views dimensions and its containers dimensions. For example, the x position of the view within its container could be determined like this: int x = (container.getWidth() / 2) - (view.getWidth() / 2); And a similar approach would apply to the height. - Mike Ortiz

2 Answers

14
votes

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);
}
2
votes

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);