前面一篇写的是利用postInvalidate函数和onDraw函数来实现简单动画的,这里要说的第二种方法我感觉比较类似,是利用擦除函数来完成这个简单动画的制作。简单的说就是先利用和上一篇中一样的Paint(画笔),Canvas(画布)这些类来进行绘画,然后在进行下次绘画之前将前面一次的绘画擦除,在进行新的绘画,在时间很快的情况下就是一个简单的动画了,擦除绘画就是将画布的颜色恢复就行。个人觉得这和前面一种做法差不多。这里还是用画线为例。
public class SlideViewSingleSelfVideoActivity extends SurfaceView implements SurfaceHolder.Callback {
protected SurfaceHolder surfaceholder;
// private MyThread thread;
private static final int SPEEN_DISTANCE = 5; // 中间线每次刷新移动的距离
private Paint paint; // 画笔对象的引用
private int slideTop; // 中间滑动线的最顶端位置
private int slideBottom; // 中间滑动线的最底端位置
private int slideLeft; // 中间滑动线的最左边位置
private int slideRight; // 中间滑动线的最右边位置
public SlideViewSingleSelfVideoActivity(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
surfaceholder = getHolder(); // 获取SurfaceHolder对象
surfaceholder.addCallback(this); // 添加回调
surfaceholder.setFormat(PixelFormat.TRANSPARENT); // 设置为透明
// setZOrderOnTop(true); // 设置视图在顶层
}
public void clearDraw() {
synchronized(surfaceholder) {
Canvas canvas = surfaceholder.lockCanvas();
canvas.drawColor(Color.BLUE);// 清除画布
surfaceholder.unlockCanvasAndPost(canvas);
}
}
public void Draw(int y) {
synchronized(surfaceholder) {
Canvas canvas = surfaceholder.lockCanvas();
canvas.drawColor(Color.BLUE); // 这里是绘制背景
paint = new Paint();
paint.setAntiAlias(true); // 反锯齿
//获取屏幕的宽高
int width = canvas.getWidth();
slideLeft = 50;
slideRight = width - slideLeft;
slideTop = y;
slideBottom = y + 5;
//绘制中间的线,每次刷新界面,中间的线往下移动SPEEN_DISTANCE
paint.setColor(Color.RED); // 将画笔设置成红色
canvas.drawRect(slideLeft, slideTop, slideRight, slideBottom, paint);
surfaceholder.unlockCanvasAndPost(canvas);
}
}
@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
@Override
public void surfaceCreated(SurfaceHolder arg0) {
// TODO Auto-generated method stub
}
@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
// TODO Auto-generated method stub
}
}
然后在主Activity中调用。
/*
* 刷新屏幕,移动绘制线
*/
private SlideViewSingleSelfVideoActivity m_vVideoViewDraw = null;
private int lastY = 350;
private TimerTask mMoveTask;
private void start() {
m_vVideoViewDraw =(SlideViewSingleSelfVideoActivity)findViewById(SystemView.getViewID(this,"videoview_surface_draw"));
m_vVideoViewDraw.setVisibility(View.VISIBLE);
mMoveTask = new TimerTask() {
@Override
public void run() {
m_vVideoViewDraw.Draw(lastY);
lastY += 20; // 向下
if(lastY > 1100) {
m_vVideoViewDraw.clearDraw();
lastY = 350;
}
}
};
mVideoRecordTimer.schedule(mMoveTask, 0,100);
}
因为不是demo,所以代码可能不详实。