draw Text Center on Canvas - Android Graphics

Android examples for Graphics:Canvas

Description

draw Text Center on Canvas

Demo Code


//package com.java2s;

import android.graphics.Canvas;

import android.graphics.Paint;

import android.graphics.Rect;
import android.graphics.RectF;

public class Main {
    public static void drawTextCenter(Canvas canvas, RectF rectf, String s,
            Paint paint) {//from  w  w  w .  ja v  a  2  s .c  o m
        Rect rect = new Rect();
        paint.getTextBounds(s, 0, s.length(), rect);
        canvas.drawText(
                s,
                rectf.left + (rectf.width() - (float) rect.width()) / 2.0F,
                rectf.top + (rectf.height() + (float) rect.height()) / 2.0F,
                paint);
    }

    public static void drawTextCenter(Canvas canvas, RectF rectf, String s,
            String s1, Paint paint, Paint paint1) {
        Rect rect = new Rect();
        paint.getTextBounds(s, 0, s.length(), rect);
        float f = rectf.left + (rectf.width() - (float) rect.width())
                / 2.0F;
        float f1 = rectf.top + (rectf.height() + (float) rect.height())
                / 2.0F;
        canvas.drawText(s, f, f1, paint);
        Rect rect1 = new Rect();
        paint1.getTextBounds(s, 0, s.length(), rect1);
        canvas.drawText(s1, 6F + (f + (float) rect.width()),
                (f1 - (float) rect.height()) + (float) rect1.height(),
                paint1);
    }
}

Related Tutorials