Android — putting the GLSurfaceView.Renderer to sleep (as in Thread.sleep(20)) outside of the OnDrawFrame Method

好久不见. 提交于 2019-12-14 03:57:40

问题


I want to control the rendering rate of my GLSurfaceView.Renderer. I implemented a thread in the class that extends GLSurfaceView, and put it to sleep periodically in a while(true) loop, which did nothing to slow down the renderer. There's a good answer here that suggests putting the GL Thread to sleep by using a Thread.sleep within the Renderer.onDrawFrame() method. I'd like to handle it from outside the Renderer class. How can that be done when an explicit call requires passing in a GL10 object? Thanks.


回答1:


Don't extend GLSurfaceView. If you're not already, keep the renderer as a variable in your activity class:

public class MyActivity extends Activity {

    protected GLSurfaceView mGLView;
    protected GraphicsRenderer graphicsRenderer; // keep reference to renderer

    protected void initGraphics() {

        graphicsRenderer = new GraphicsRenderer(this);

        mGLView = (GLSurfaceView) findViewById(R.id.graphics_glsurfaceview1);
        mGLView.setEGLConfigChooser(true);         
        mGLView.setRenderer(graphicsRenderer);

        graphicsRenderer.setFrameRate(30);


    }
}

Then you can create a method in your renderer to control the frame rate:

public class GraphicsRenderer  implements GLSurfaceView.Renderer {

    private long framesPerSecond;
    private long frameInterval; // the time it should take 1 frame to render
    private final long millisecondsInSecond = 1000;

    public void setFrameRate(long fps){

        framesPerSecond = fps;

        frameInterval= millisecondsInSeconds / framesPerSecond;

    }


    public void onDrawFrame(GL10 gl) {

        // get the time at the start of the frame
        long time = System.currentTimeMillis();

        // drawing code goes here

        // get the time taken to render the frame       
        long time2 = System.currentTimeMillis() - time;

        // if time elapsed is less than the frame interval
        if(time2 < frameInterval){          
            try {
                // sleep the thread for the remaining time until the interval has elapsed
                Thread.sleep(frameInterval - time2);
            } catch (InterruptedException e) {
                // Thread error
                e.printStackTrace();
            }
        } else {
            // framerate is slower than desired
        }
    }

}


来源:https://stackoverflow.com/questions/5888284/android-putting-the-glsurfaceview-renderer-to-sleep-as-in-thread-sleep20

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!