1

如果我在 android 4.xx 下运行我的程序(Canvas、SurfaceView),我会得到稳定的 60 FPS,但在 2.3.3 FPS 下会增加到 75-80。如何在 android 2.3.3 下更轻松地实现 60 FPS (vsync)?

更新(一些绘图代码):

public class game extends Activity implements OnTouchListener 
{      
    FastRenderView renderView;

    @Override   
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        renderView = new FastRenderView(this);
        renderView.setOnTouchListener(this);            
        setContentView(renderView);             
    }      

    protected void onResume() {
        super.onResume();
        renderView.resume();
    }

    protected void onPause() {
        super.onPause();        
        renderView.pause();
    }    

    class FastRenderView extends SurfaceView implements Runnable  {
        Thread renderThread = null;
        SurfaceHolder holder;
        volatile boolean running = false;

        public FastRenderView(Context context) {
            super(context); 


            holder = getHolder();     

        private void drawSurface(Canvas canvas) 
        {
        // Draw all                                                                    
        }

        public void resume() {          
            running = true;
            renderThread = new Thread(this);
            renderThread.start();        
        }

        public void pause() {        
            running = false;                        
            while(true) {
                try {
                    renderThread.join();
                    break;
                } catch (InterruptedException e) {
                    // retry
                }
            }
            renderThread = null;        
        }

        public void run() {
            while(running) {  
                if(!holder.getSurface().isValid())
                    continue;

                Canvas canvas = holder.lockCanvas();            
                drawSurface(canvas);                                          
                holder.unlockCanvasAndPost(canvas);            
            }
        }               

    }

Update2:找到简单的解决方案(感谢 Google):

int max_fps = 60;
int frame_period = 1000/max_fps;
long beginTime;
long timeDiff;
int sleepTime;

public void run() {
  sleepTime = 0;
  while(running) {  
  if(!holder.getSurface().isValid())
   continue; 
  beginTime = System.currentTimeMillis();                
  Canvas canvas = holder.lockCanvas();            
  drawSurface(canvas);                                          
  holder.unlockCanvasAndPost(canvas);
  timeDiff = System.currentTimeMillis() - beginTime;                         
  sleepTime = (int)(frame_period - timeDiff); // calculate sleep time
  if (sleepTime > 0) {
    try { Thread.sleep(sleepTime); } catch (InterruptedException e) {}
  }
}
4

1 回答 1

1

vsync 是在 jelly bean 版本(项目黄油)中引入的。在较旧的 android 版本上无法执行此操作。如果您想了解完整的故事,请观看此视频:http ://www.youtube.com/watch?v=Q8m9sHdyXnE 。值得一看!

于 2013-07-15T11:28:21.567 回答