draw Text In Center on Canvas - Android Graphics

Android examples for Graphics:Canvas

Description

draw Text In Center on Canvas

Demo Code


//package com.java2s;
import android.graphics.Canvas;
import android.graphics.Paint;

public class Main {

    public static void drawTextInCenter(Canvas canvas, Paint paint,
            String text, float centerX, float centerY) {
        float bottom = paint.getFontMetrics().bottom;
        canvas.drawText(/*from   w ww. j  a  va  2 s.  c  om*/
                text,
                (float) (centerX - measureTextWidth(text, paint) * 0.5),
                (float) (0.5 * measureTextHeight(paint) - bottom + centerY),
                paint);
    }

    public static float measureTextWidth(String text, Paint paint) {
        float width = paint.measureText(text);

        return width;
    }

    public static float measureTextHeight(Paint paint) {
        Paint.FontMetrics fm = paint.getFontMetrics();
        float height = fm.bottom - fm.top;

        return height;
    }
}

Related Tutorials