Android — putting the GLSurfaceView.Renderer to sl

2019-07-17 03:33发布

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条回答
干净又极端
2楼-- · 2019-07-17 04:01

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
        }
    }

}
查看更多
登录 后发表回答