Skip to content

Cam Selector (Lens Facing)

Lucas Yuji edited this page Nov 3, 2022 · 9 revisions

Cam Selector

There are 2 selectors, CamSelector.Back and CamSelector.Front

You can use and switch cameras like any state from compose, here is an example:

@Composable
fun Camera() {
  var camSelector by rememberCamSelector(CamSelector.Back) // Or CamSelector.Front
  CameraPreview(camSelector = camSelector) {
    Button(onClick = {
      camSelector = camSelector.reverse // Switch Camera
    }) { 
       Text("Switch") 
    }
  }
}

Why use rememberCamSelector?

The rememberCamSelector restore on configuration changed, using rememberSaveable internally. If you DON'T want that restore on configuration changed, you can use remember like the example below:

// WITHOUT RESTORING ON CONFIGURATION CHANGED
val camSelector by remember { mutableStateOf(CamSelector.Back) }

Switch Cameras

To switch cameras from front to back or vice versa, use CamSelector.reverse:

Button(onClick = {
  camSelector = camSelector.reverse // Switch Camera
}) { /* code... /* }

On Switch camera

If you want callbacks when switching cameras, check it out on onSwitchToFront(Bitmap), onSwitchToBack(Bitmap), and onPreviewStreamChanged

  • onSwitchToFront(Bitmap): composable callback triggered when the camera preview is switched to the front camera, it contains the latest bitmap frame from the camera as a parameter.
  • onSwitchToBack(Bitmap): is a composable callback triggered when the camera preview is switched to the back camera, it contains the latest bitmap frame from the camera as a parameter.
  • onPreviewStreamChanged: is a generic callback that's triggered when the camera is switched.
Clone this wiki locally