首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > Android >

关于画三角行的有关问题

2012-09-15 
求助:关于画三角行的问题我想随机画N个三角形,帧率60fs,就重写了SurfaceView,但是屏幕会不停的闪,中途按返

求助:关于画三角行的问题
我想随机画N个三角形,帧率60fs,就重写了SurfaceView,但是屏幕会不停的闪,中途按返回建,还会出现force close,请各位高手帮忙看一下(不过我现在已经用新的方法实现了)
  public class MyView extends SurfaceView implements SurfaceHolder.Callback {

  private SurfaceHolder holder;  
  public MyView(Context context) {
  super(context);
  holder = this.getHolder();//获取holder
  holder.addCallback(this);  
  }
   
  public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
  // TODO Auto-generated method stub

  }

  public void surfaceCreated(SurfaceHolder holder) {
  new Thread(new MyThread()).start();
   
  }

  public void surfaceDestroyed(SurfaceHolder holder) {
  // TODO Auto-generated method stub
   
  }

  class MyThread implements Runnable {
  public void run() {  
  Paint mPaint = new Paint();
  mPaint.setStyle(Style.FILL);
  mPaint.setAntiAlias(true);
  Random random = new Random(System.currentTimeMillis());  
  Canvas canvas = null;
  int rotate = 0;
   
  while (rotate < 500) {
  //Date curr = new Date();
  rotate=rotate+1;
  try{
  canvas = holder.lockCanvas();//获取canvas
  mPaint.setColor(new Color().rgb(random.nextInt(255), random.nextInt(255), random
  .nextInt(255)));
  mPaint.setStrokeWidth(2);/*设置paint的外框宽度*/
  Path mPath = new Path();
  mPath.moveTo(random.nextInt(450), random.nextInt(600));
  mPath.lineTo(random.nextInt(300), random.nextInt(400));
  mPath.lineTo(random.nextInt(200), random.nextInt(300));
  mPath.close();
  canvas.drawPath(mPath, mPaint);
   
  Thread.sleep(Math.max(0, 17-(new Date().getTime()))); //休眠  
  }catch (InterruptedException e) {
  e.printStackTrace();
  }finally{
  holder.unlockCanvasAndPost(canvas); //解锁canvas,提交画好的图像
  }
  }
  }
  }
  }

[解决办法]
SurfaceView是frontbuffer和backbuffer交替显示的,每次Post交替一次,按你这样写两个Buffer是不一样的所有奇数的Post画在一起,偶数的画在另外个Buffer,运行起来就会闪了。延时长一点就看的出来了。
应用上加缓冲就可以了。

Java code
          //加缓冲      private Paint[] paints=new Paint[2];          private Path[]  paths=new Path[2];                    //这样更新canvas          paints[0]=paints[1];          paints[1]=mPaint;             paths[0]=paths[1];          paths[1]=mPath;                 if(paints[0]!=null) //画的时候还有画一次的            canvas.drawPath(paths[0], paints[0]);          canvas.drawPath(mPath, mPaint); 

热点排行