目标:逐字绘制文字
结果:文字绘制在不同的图层上: 要绘制的文字:Hello World !!!
公共类DrawThread扩展Thread { public static final String TAG = DrawThread.class.getSimpleName();
private SurfaceHolder surfaceHolder;
private String word;
private Paint paint;
public DrawThread(SurfaceHolder surfaceHolder, String word, Paint paint){
this.surfaceHolder = surfaceHolder;
this.word = word;
this.paint = paint;
}
@Override
public void run() {
String letterToDraw;
int wordLength = word.length();
int counter = 0;
while (counter < wordLength){
Canvas canvas = surfaceHolder.lockCanvas(null);
letterToDraw = word.charAt(counter)+"";
canvas.drawText(letterToDraw, 20 + counter*20, 40, paint);
surfaceHolder.unlockCanvasAndPost(canvas);
counter++;
try {
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class MySurfaceView扩展了SurfaceView { private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
public MySurfaceView(Context context) {
super(context);
init();
}
public MySurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MySurfaceView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init(){
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(1);
paint.setTextSize(45);
paint.setColor(Color.CYAN);
}
public void drawText(){
DrawThread drawThread = new DrawThread(getHolder(), "Hello World!!!", paint);
drawThread.run();
}
}
答案 0 :(得分:1)
问题在于SurfaceView是双缓冲还是三缓冲,并且您不是每次都重绘整个屏幕。因此,替代字母最终会在每个缓冲区中结束。
每次拨打Canvas#lockCanvas()
时,都应该清除并重绘整个屏幕。然后创建一个内部循环,用于绘制从0到counter
的字母,而不只是counter
处的字母。
(你还需要考虑每个字母的宽度,这样它们就不会相互叠加,但这是一个完全不同的东西。)
有关Android图形和SurfaceView行为的一些背景资料here。