android中,用list记录画笔轨迹(想实现播放绘图功能),点击绘图,可以一次性将记录的轨迹画出,但是如果让轨迹一点一点画,就是断断续续,代码附上,请大神速来赐教

八爷 发布于 2014/01/26 15:07
阅读 1K+
收藏 1

代码:

public class MainActivity extends Activity  {

private Button currentDraw = null ;
private Button playDraw = null ;
//用于呈现所画图形
private SurfaceView view = null ;
//用于获取画布Canvas
private SurfaceHolder surfaceHolder = null ;
private Point point = null ;
//储存手指在屏幕上画过的点
private List<Point> list = null ;
//定时调度,慢慢将list集合中的点画出来,即播放绘图
private Timer timer = null ;
private TimerTask playtask = null ;
private Paint paint = null ;
//记录开始点
private float startX ,startY ;
    //记录下一点
private float endX ,endY ;
private int next ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

currentDraw = (Button) super.findViewById(R.id.draw) ;
playDraw = (Button) super.findViewById(R.id.play) ;
view = (SurfaceView) super.findViewById(R.id.surface) ;
surfaceHolder = view.getHolder() ;
list = new ArrayList<Point>() ;
timer = new Timer() ;
//实例化并设置画笔相关属性
paint = new Paint() ;
paint.setAntiAlias(true) ;
paint.setDither(true) ;
paint.setColor(Color.GREEN) ;
paint.setStrokeWidth(5) ;
paint.setStrokeCap(Paint.Cap.ROUND) ;
paint.setStyle(Paint.Style.STROKE) ;

currentDraw.setOnClickListener(new currentDrawListener()) ;
playDraw.setOnClickListener(new playDrawListener()) ;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
point = new Point((int)event.getX(), (int)event.getY()) ;
switch(event.getAction()){
case MotionEvent.ACTION_DOWN :
list.add(point) ;
break ;
case  MotionEvent.ACTION_MOVE :
list.add(point) ;
break ;
case MotionEvent.ACTION_UP :
list.add(point) ;
break ;
}
return true ;
}

// 绘图监听器
private class currentDrawListener implements OnClickListener{


@Override
public void onClick(View v) {
if(list.size()>1){
currentDraw() ;
}
}

}

//播放绘图监听器
private class playDrawListener implements OnClickListener{


@Override
public void onClick(View v) {
if(list.size()>1){
startX = list.get(0).x ;
startY = list.get(0).y ;
next = 0 ;
}
playtask = new TimerTask() {

@Override
public void run() {
next++ ;
playDraw(next) ;
}
};
//每50毫秒画一次线
timer.schedule(playtask, 0, 50) ;
}

}

//播放绘图
protected void playDraw(int next) {
if(next < list.size()){
//取得画布
Canvas canvas = surfaceHolder.lockCanvas() ;
//取得下一个点
endX = list.get(next).x ;
endY = list.get(next).y ;
//画线
canvas.drawLine(startX, startY, endX, endY, paint) ;
//将起点设置为下一个点
startX = endX ;
startY = endY ;
surfaceHolder.unlockCanvasAndPost(canvas) ;
}
}

//一次性绘图
public void currentDraw() {
startX = list.get(0).x ;
startY = list.get(0).y ;
Canvas canvas = surfaceHolder.lockCanvas() ;
for(int i=0;i<list.size();i++){
endX = list.get(i).x ;
endY = list.get(i).y ;
canvas.drawLine(startX, startY, endX, endY, paint) ;
startX = endX ;
startY = endY ;
}
surfaceHolder.unlockCanvasAndPost(canvas) ;
}


}

将轨迹一次性画出:

播放绘图(一点一点的画):


加载中
返回顶部
顶部