当前位置: 代码迷 >> Android >> Android中SurfaceView绘制触摸轨迹时出现的闪烁有关问题
  详细解决方案

Android中SurfaceView绘制触摸轨迹时出现的闪烁有关问题

热度:61   发布时间:2016-05-01 20:02:49.0
Android中SurfaceView绘制触摸轨迹时出现的闪烁问题
今天在处理触屏轨迹的绘制时,用到了SurfaceView,建立Path对象,在点击时开始设置Path对象,滑动过程中记录触摸点,离开后重新设置Path对象,因不能阻塞主线程,所以新建了一个子线程来不断刷新屏幕,也就是将path不断绘制。但是,接着就出现了一个问题:屏幕中每条轨迹线的终点都会有一小段直线段不断闪烁。猜测可能是lockCanvas()获取的对象区域不一样,就试着使用了lockCanvas(Rect re),但是,运行后发现还是没有解决问题;接着想到可能是因为每次lockCanvas()后获取的对象不同,就在主线程中添加了一个Canvas对象,每次都在Canvas对象中修改画面,然后提交显示,但是,程序运行后效果丝毫没有改变!shit!程序代码如下:
package com.tobacco.touchdraw;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.SurfaceHolder.Callback;
import android.view.View.OnTouchListener;
public class MySurfaceView extends SurfaceView implements Callback,OnTouchListener,Runnable{ private SurfaceHolder sfh; private Canvas canvas; private Paint paint; private float lastX,lastY; private Path path; private boolean flag; public MySurfaceView(Context context) {  super(context);  sfh=this.getHolder();  sfh.addCallback(this);  paint=new Paint();  paint.setColor(Color.RED);  paint.setAntiAlias(true);  paint.setStrokeWidth(5);  paint.setStyle(Paint.Style.STROKE);  paint.setStrokeCap(Paint.Cap.ROUND);  path=new Path();   } public void myDraw(MotionEvent e){  int action=e.getAction();  switch(action){  case MotionEvent.ACTION_DOWN:   path.moveTo(e.getX(),e.getY());   lastX=e.getX();   lastY=e.getY();   break;  case MotionEvent.ACTION_MOVE:   path.quadTo(lastX,lastY,e.getX(),e.getY());   lastX=e.getX();   lastY=e.getY();   break;  case MotionEvent.ACTION_UP:   //path.quadTo(lastX,lastY,e.getX(),e.getY());   path.reset();   break;  }     } @Override public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {     } @Override public void surfaceCreated(SurfaceHolder holder) {  flag=true;  setOnTouchListener(this);  new Thread(this).start();   } @Override public void surfaceDestroyed(SurfaceHolder holder) {  flag=false; } @Override public boolean onTouch(View v, MotionEvent event) {  myDraw(event);  return true; } @Override public void run() {  while(flag){   long start=System.currentTimeMillis();   canvas=sfh.lockCanvas();   if(canvas!=null){    canvas.drawPath(path,paint);    sfh.unlockCanvasAndPost(canvas);   }   long end=System.currentTimeMillis();   try{    if(end-start<100){     Thread.sleep(100-(end-start));    }   }   catch(Exception e){   }  }   }}
  相关解决方案