Center text inside a circle on a canvas

Posted by jax on Stack Overflow See other posts from Stack Overflow or by jax
Published on 2010-05-17T06:04:53Z Indexed on 2010/05/17 6:10 UTC
Read the original article Hit count: 198

Filed under:

I have the coordinates of the center of a circle where I need to draw some text. The circle may be larger or smaller depending on the attributes I have specified. I have set the center horizontally using mTextBrush.setTextAlign(Align.CENTER);. The problem is that I can't figure out a way to center the text vertically. (See "Draw the counter" below)

        //Text Brush setup
    mTextBrush = new Paint(Paint.ANTI_ALIAS_FLAG);
    mTextBrush.setColor(Color.BLACK);
    mTextBrush.setTextSize(1/10*mMaxSize);
    mTextBrush.setTextAlign(Align.CENTER);
    mTextBrush.setStyle(Paint.Style.STROKE);




    private void drawSmallTimer(Canvas canvas) {
    //Variable cache
    int radiusLocalCache = this.mRadius;

    int cx = radiusLocalCache+(radiusLocalCache/2);
    int cy = radiusLocalCache-(radiusLocalCache/2);
    int radius = radiusLocalCache/3;

    //Draw the background circle
    canvas.drawCircle(cx, cy, radius, mBackgroundBrush);

    //Draw the outline stroke
    canvas.drawCircle(cx, cy, radius, mStrokeBrush);

    //Draw the counter
    String text = String.valueOf(mCounter);
    canvas.drawText(text, cx, cy, mTextBrush);
}

© Stack Overflow or respective owner

Related posts about android