class ComposeCameraXActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
SimpleCameraPreview()
}
}
@Composable
fun SimpleCameraPreview() {
val lifecycleOwner = LocalLifecycleOwner.current
val context = LocalContext.current
val cameraProviderFuture = remember { ProcessCameraProvider.getInstance(context) }
AndroidView(
factory = { ctx ->
val preview = PreviewView(context).apply {
this.scaleType = scaleType
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
implementationMode = PreviewView.ImplementationMode.COMPATIBLE
}
val executor = ContextCompat.getMainExecutor(ctx)
cameraProviderFuture.addListener({
val cameraProvider = cameraProviderFuture.get()
bindPreview(
lifecycleOwner,
preview,
cameraProvider,
)
}, executor)
preview
},
modifier = Modifier.fillMaxSize(),
)
}
private fun bindPreview(
lifecycleOwner: LifecycleOwner,
previewView: PreviewView,
cameraProvider: ProcessCameraProvider
) {
val preview = androidx.camera.core.Preview.Builder().build()
val cameraSelector: CameraSelector = CameraSelector.Builder()
.requireLensFacing(CameraSelector.LENS_FACING_BACK)
.build()
preview.setSurfaceProvider(previewView.surfaceProvider)
val camera = cameraProvider.bindToLifecycle(lifecycleOwner, cameraSelector, preview)
camera.cameraControl.cancelFocusAndMetering()
}
}