Development

How to display VerticalText in Android

Recently I was working on a project where I had free reign over the UI, and felt that it would be very nice to have some vertically oriented text. On searching through the Android API docs, I found that rotating Views isn’t supported directly, but a quick Google search found a number of approaches.

Before we begin, let’s discuss what I was trying to achieve. I wanted the text rotated through 90 degrees anti-clockwise. To achieve this we need to move our text to the right by a distance equal to its own height, down by a distance equal to its own width, and then rotate it by -90 around its bottom left corner. So, if we start with the following text:

Original Text

We want this to appear as follows:

Final Text

Let’s create a new class named VerticalTextView:

package ge.droid.examples;

import android.content.Context;
import android.graphics.Canvas;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.Gravity;

public class VerticalTextView extends android.support.v7.widget.AppCompatTextView {
    final boolean topDown;

    public VerticalTextView(Context context, AttributeSet attrs){
        super(context, attrs);

        final int gravity = getGravity();
        if (Gravity.isVertical(gravity) && (gravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
            setGravity((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) | Gravity.TOP);
            topDown = false;
        } else {
            topDown = true;
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(heightMeasureSpec, widthMeasureSpec);

        setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        TextPaint textPaint = getPaint();
        textPaint.setColor(getCurrentTextColor());
        textPaint.drawableState = getDrawableState();

        canvas.save();

        if (topDown) {
            canvas.translate(getWidth(), 0);
            canvas.rotate(90);
        } else {
            canvas.translate(0, getHeight());
            canvas.rotate(-90);
        }

        canvas.translate(getCompoundPaddingLeft(), getExtendedPaddingTop());

        getLayout().draw(canvas);
        canvas.restore();
    }
}

XML code:

    <ge.droid.examples.VerticalTextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="bottom|right" android:text="Vertical text" />

We need to set the gravity to bottom|right in order to get the text in the orientation that we want.

The result:

 

Tags
Close