-
Notifications
You must be signed in to change notification settings - Fork 14
Flash & Torch
Using Flash or Torch is a little bit different from other configurations, it needs to use CameraState's remembers to work well, without bugs or even crashes.
Let's start with Flash mode, in the below example, it starts with flash mode off, and the button is clicked reverse it.
val cameraState = rememberCameraState()
var flashMode by cameraState.rememberFlashMode(
initialFlashMode = FlashMode.Off // or FlashMode.On or FlashMode.Auto, default is FlashMode.Off
useSaver = true // to restore on configuration changed, default is true
)
CameraPreview(
cameraState = cameraState,
flashMode = flashMode,
) {
Button(
onClick = { flashMode = flashMode.reverse }
) {
Text("Flash $flashMode")
}
}
In this case, when FlashMode.reverse
is used, it's only for FlashMode.On
and FlashMode.Off
.
If you need to use FlashMode.Auto
, you'll need to implement by yourself but there's an example in the sample project.
The CameraState.rememberFlashMode
restore on configuration changed, and disable by itself when there's no flash in the CamSelector
Different from Flash mode, if the torch is enabled, it'll always stay lights up.
It's very simple to use torch in Camposer, here is an example:
val cameraState = rememberCameraState()
var torch by cameraState.rememberTorch(
initialTorch = false // or true, default is false
useSaver = true // to restore on configuration changed, default is true
)
CameraPreview(
cameraState = cameraState,
torch = torch,
) {
Button(
onClick = { torch = !torch }
) {
Text("Torch $torch")
}
}
The CameraState.rememberTorch
restore on configuration changed, and disable by itself when there's no flash in the CamSelector
If you want to check if there's flash in the currently CamSelector, use CameraState.hasFlashUnit
, and it also can be a composable state:
val cameraState = rememberCameraState()
val hasFlashUnit by rememberUpdatedState(cameraState.hasFlashUnit)