Java tutorial
//package com.java2s; //License from project: Apache License 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; 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; } } }