TextView on Center Draw - Android User Interface

Android examples for User Interface:TextView

Description

TextView on Center Draw

Demo Code


//package com.java2s;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.view.Gravity;
import android.widget.TextView;

public class Main {
    private static void onCenterDraw(TextView view, Canvas canvas,
            Drawable drawable, int gravity) {
        int drawablePadding = view.getCompoundDrawablePadding();
        int ratio = 1;
        float total;

        switch (gravity) {
        case Gravity.END:
            ratio = -1;//from   ww w .  ja  v a 2s .  c  om
        case Gravity.START:
            total = view.getPaint().measureText(view.getText().toString())
                    + drawable.getIntrinsicWidth() + drawablePadding
                    + view.getPaddingLeft() + view.getPaddingRight();
            canvas.translate(ratio * (view.getWidth() - total) / 2, 0);
            break;
        case Gravity.BOTTOM:
            ratio = -1;
        case Gravity.TOP:
            Paint.FontMetrics fontMetrics = view.getPaint()
                    .getFontMetrics();
            total = fontMetrics.descent - fontMetrics.ascent
                    + drawable.getIntrinsicHeight() + drawablePadding
                    + view.getPaddingTop() + view.getPaddingBottom();
            canvas.translate(0, ratio * (view.getHeight() - total) / 2);
            break;
        }
    }
}

Related Tutorials