views:

632

answers:

2

How can you display upside down text with a textview in Android?

In my case I have a 2 player game, where they play across from each other. I want to display test to the second player oriented to them.


This was the solution I implemented after AaronMs advice

The class that does the overriding, bab.foo.UpsideDownText

package bab.foo;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.widget.TextView;

public class UpsideDownText extends TextView {

    //The below two constructors appear to be required
    public UpsideDownText(Context context) {
        super(context);
    }

    public UpsideDownText(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    @Override
    public void onDraw(Canvas canvas) {
        //This saves off the matrix that the canvas applies to draws, so it can be restored later. 
        canvas.save(); 

        //now we change the matrix
        //We need to rotate around the center of our text
        //Otherwise it rotates around the origin, and that's bad. 
        float py = this.getHeight()/2.0f;
        float px = this.getWidth()/2.0f;
        canvas.rotate(180, px, py); 

        //draw the text with the matrix applied. 
        super.onDraw(canvas); 

        //restore the old matrix. 
        canvas.restore(); 
    }
}

And this is my XML layout:

<bab.foo.UpsideDownText 
    android:text="Score: 0" 
    android:id="@+id/tvScore" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"
    android:textColor="#FFFFFF" 
    >
</bab.foo.UpsideDownText>
+2  A: 

I haven't tried doing this myself, but I think it should work.

Override the view's onDraw method, call it's super passing in the canvas, then after call the rotate method on the canvas passed to it, passing in either 180 or Math.PI, depending on whether it works in degrees or radians.

AaronM
Anyone have ideas why that doesn't work?
Ravedave
You can just scale by -1 on the Y axis too :)
Romain Guy
Thanks I removed my comment asking for further help since that code didn't work :). Thanks for the answer it pointed me in the right direction.
Ravedave
A: 

I copied the code, and tried it on a simple widget, but it didn't work. Someone with a working code please post here.

John
"It didn't work" Can you provide more details?
Ravedave
I mean the text was not shown upside down.
John