cameraViewEx / com.priyankvasa.android.cameraviewex / CameraView / setPreviewFrameListener

setPreviewFrameListener

fun setPreviewFrameListener(listener: (<ERROR CLASS>) -> Unit): CameraView

Platform and version requirements: JVM

Set preview frame listener. Be careful while using this listener as it is invoked on each frame, which could be 60 times per second if frame rate is 60 fps. Ideally, next frame should only be processed once current frame is done processing. Continuously launching background tasks for each frame is is not memory efficient, the device will run out of memory very quickly and force close the app.

CameraView(context).apply {

    val processing = AtomicBoolean(false)

    addCameraOpenedListener { /* Camera opened. */ }

    setPreviewFrameListener { image: Image ->

        if (processing.compareAndSet(false, true)) {

            val result = GlobalScope.async { /* Some background image processing task */ }

            result.invokeOnCompletion { t ->
                val output = result.getCompleted()
                /* ...  use the output ... */
                // Set processing flag to false
                processing.set(false)
            }
        }
    }

    addPictureTakenListener { imageData: ByteArray -> /* Picture taken successfully. */ }

    addCameraClosedListener { /* Camera closed. */ }
}

Parameters

listener - lambda with image of type Image as its argument which is the preview frame. It is always of type android.graphics.ImageFormat.YUV_420_888

Return
instance of CameraView it is called on