Skip to content

Instantly share code, notes, and snippets.

@ln-12
Last active August 21, 2023 09:28
Show Gist options
  • Save ln-12/60922258048c81d99f2259e1b6a1615b to your computer and use it in GitHub Desktop.
Save ln-12/60922258048c81d99f2259e1b6a1615b to your computer and use it in GitHub Desktop.
Jetpack Compose example usage of the new ImageAnalysis MlKitAnalyzer (https://android-developers.googleblog.com/2022/08/camerax-12-is-now-in-beta.html)
@Composable
fun CameraPreview(
modifier: Modifier = Modifier,
cameraSelector: CameraSelector = CameraSelector.DEFAULT_BACK_CAMERA,
scaleType: PreviewView.ScaleType = PreviewView.ScaleType.FILL_CENTER,
onBarCodesFound: (barCodes: List<Barcode>) -> Boolean,
) {
val lifecycleOwner = LocalLifecycleOwner.current
val context = LocalContext.current
var barcodeScanner = remember<BarcodeScanner?> { null }
AndroidView(
modifier = modifier,
factory = {
val previewView = PreviewView(context).apply {
this.scaleType = scaleType
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
// Preview is incorrectly scaled in Compose on some devices without this
implementationMode = PreviewView.ImplementationMode.COMPATIBLE
}
val cameraController = LifecycleCameraController(context)
cameraController.bindToLifecycle(lifecycleOwner)
cameraController.cameraSelector = cameraSelector
previewView.controller = cameraController
val options = BarcodeScannerOptions.Builder()
.setBarcodeFormats(Barcode.FORMAT_QR_CODE)
.build()
barcodeScanner?.close()
barcodeScanner = BarcodeScanning.getClient(options)
cameraController.clearImageAnalysisAnalyzer()
val scanner = barcodeScanner!!
val executor = ContextCompat.getMainExecutor(context)
val analyzer = MlKitAnalyzer(
listOf(scanner),
COORDINATE_SYSTEM_VIEW_REFERENCED,
executor
) { result ->
val barcodes = result.getValue(scanner)
if (barcodes != null && barcodes.size > 0) {
onBarCodesFound(barcodes)
}
}
cameraController.setImageAnalysisAnalyzer(executor, analyzer)
previewView
}
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment