29

Androidでテキストビューを使用して逆さまのテキストを表示するにはどうすればよいですか?

私の場合、2人用のゲームがあり、お互いに向かい合ってプレイします。彼らに向けられたセカンドプレイヤーにテストを見せたい。


これは、AaronMsのアドバイスの後に実装したソリューションでした

オーバーライドを行うクラス、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(); 
    }
}

そしてこれが私のXMLレイアウトです:

<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>
4

3 に答える 3

5

私はこれを自分でやろうとしたことはありませんが、うまくいくはずです。

ビューの onDraw メソッドをオーバーライドし、キャンバスでスーパーパスを呼び出してから、渡されたキャンバスでrotateメソッドを呼び出した後、角度またはラジアンで機能するかどうかに応じて、180 または Math.PI を渡します。

于 2010-04-01T05:35:46.753 に答える
3

以下のコードは完全に機能しています (ちなみにありがとう)。不足しているコンストラクターを追加してみてください。それが機能しない場合、問題はAndroidバージョンのメインが2.1であることです

package p.c;

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

public class TextViewUD extends TextView {

    public TextViewUD(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    public TextViewUD(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    public TextViewUD(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.save();

        float py = this.getHeight()/2.0f;
        float px = this.getWidth()/2.0f;
        Log.d("testUD", String.format("w: %d h: %d ", this.getWidth(), this.getHeight()));
        Log.d("testUD", String.format("w: %f h: %f ", py, px));
        canvas.rotate(180, px, py);

        super.onDraw(canvas);

        canvas.restore();
    }
}
于 2011-06-20T15:13:46.897 に答える