android 关于SurfaceView(二)移动那条线

移动其实就是不停的擦除上一个图画,然后画新的图画,

这里起作用的原因是因为用到了Timer

Timer是定时器,定时的调用某个任务 

SurfaceView的使用是需要在ui线程中,所以这里需要同步synchronized

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;

public class SurfaceTest extends Activity {
private Button mBtn;
private SurfaceView mSurface;
private SurfaceHolder mSurfaceHolder;
private Timer mTimer;
private MyTimerTask mTimerTask;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.surfacetest);
mBtn=(Button) this.findViewById(R.id.button1);
mBtn.setOnClickListener(new BtnClick());
mSurface=(SurfaceView) this.findViewById(R.id.surfaceView1);
mSurfaceHolder=mSurface.getHolder();
mTimer=new Timer();
mTimerTask = new MyTimerTask();
}

private class BtnClick implements View.OnClickListener {
@Override
public void onClick(View v) {
//执行任务在延时多少毫秒后,每隔多少毫秒执行一次
mTimer.schedule(mTimerTask, 0,1000);
}
}

private void drawLine(float y)
{
synchronized(mSurfaceHolder)
{
Canvas c=mSurfaceHolder.lockCanvas();
Paint p=new Paint();
p.setColor(Color.RED);
//清除
c.drawColor(Color.BLACK);
c.drawLine(10, y, 40, y, p);
mSurfaceHolder.unlockCanvasAndPost(c);
}
}

private int lasty=0;

class MyTimerTask extends TimerTask {
@Override
public void run() {
drawLine(lasty);
lasty+=20;//向下
if (lasty > mSurface.getHeight() ) {//如果到了终点,则清屏重来
ClearDraw();
lasty = 0;
}
}

}
void ClearDraw() {
synchronized(mSurfaceHolder)
{
Canvas canvas = mSurfaceHolder.lockCanvas(null);
canvas.drawColor(Color.BLACK);// 清除画布
mSurfaceHolder.unlockCanvasAndPost(canvas);
}
}
}

这里直接定义mTimer的间隔时间为1000是不对的,应该定义为一个小值,例如5,然后在实际执行任务的时候,再去判断时间

同时这里对画布的操作都是整块也是不对的,正确情况应该定义一块区域,只画需要画的区域


接下来到了我的目的,编写一个滚动播放图片的类

 

posted @ 2011-11-14 12:14  meieiem  阅读(1667)  评论(1编辑  收藏  举报