题
如何在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>
解决方案
在XML文件中添加:
android:rotation = "180"
在各个元素中显示文本颠倒。
例如:
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="TextView"
android:rotation="180"/>
其他提示
我没有自己尝试这样做,但我认为它应该起作用。
覆盖视图的OnDraw方法,将其称为“超级传递”画布,然后在传递给它的画布上调用旋转方法后,以180或Math.pi的方式传递,具体取决于它是在程度上工作还是弧度。
以下代码正常工作(顺便说一下)。尝试添加缺失的构造函数。如果不工作,我的问题是Android版本Main是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();
}
}
不隶属于 StackOverflow