Search code examples
androidcameraframe-rate

How can I achieve a desired fps with animation drawing on canvas with cameraX?


I'm using CameraX and I'd like to play animation over canvas with the same fps which used by CameraX to show Preview.

question 1:

How can I to play 60 frames animation with 30 fps (for example) of CameraX in 2 seconds, if at all possible.

question 2:

How can I get CameraX fps?


Solution

  • Regarding the first question, add a listener to your SurfaceTexture and listen to onSurfaceTextureUpdated. You can use this method as reference to know when to render your animation.

    About the second question, as far as I know there is no API in CameraX to get the FPS due to the variable nature of the a camera preview in terms of FPS. Only video recording has a fixed FPS value, for a different camera preview mode the FPS is variable. On the other hand, the camera2 API can be configured with a FPS range (min-max), so I guess the CameraX API will have something similar.

    You can alternatively compute dynamically the FPS using the onSurfaceTextureUpdated method. In the internet you will find many pages showing how to calculate a FPS. Here a small example, the code is untested, but should guide you. Call the method in onSurfaceTextureUpdated, after a few iterations you should get the active FPS.

    private long lastFpsTime = 0L;
    private float fps;
    
    private void computeFPS()
    {
        if (this.lastFpsTime != 0L)
        {
            this.fps = 1000.0f / (SystemClock.elapsedRealtime() - this.lastFpsTime);
        }
    
        this.lastFpsTime = SystemClock.elapsedRealtime();
    }