Skip to content

Instantly share code, notes, and snippets.

@Astroa7m
Created March 2, 2022 17:15
Show Gist options
  • Save Astroa7m/af19af674bfeb248ab039214d6742270 to your computer and use it in GitHub Desktop.
Save Astroa7m/af19af674bfeb248ab039214d6742270 to your computer and use it in GitHub Desktop.
@Composable
fun CameraPreview(
modifier: Modifier = Modifier,
scaleType: PreviewView.ScaleType = PreviewView.ScaleType.FILL_CENTER,
cameraSelector: CameraSelector = CameraSelector.DEFAULT_BACK_CAMERA,
onSuccess: (ssid: String, pw: String) -> Unit,
onFailure: (e: Exception) -> Unit
) {
val lifecycleOwner = LocalLifecycleOwner.current
AndroidView(
modifier = modifier,
factory = { context ->
val previewView = PreviewView(context).also { view ->
view.scaleType = scaleType
view.layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
}
val previewUseCase = Preview.Builder()
.build().also {
it.setSurfaceProvider(previewView.surfaceProvider)
}
val imageAnalysis = ImageAnalysis.Builder()
.setTargetResolution(Size(previewView.width, previewView.height))
.setBackpressureStrategy(STRATEGY_KEEP_ONLY_LATEST)
.build().apply {
setAnalyzer(
ContextCompat.getMainExecutor(context),
QRCodeWIFIAnalyzer(onSuccess, onFailure)
)
}
try {
ProcessCameraProvider.getInstance(context).get().apply {
unbindAll()
bindToLifecycle(
lifecycleOwner,
cameraSelector,
previewUseCase,
imageAnalysis
)
}
} catch (e: Exception) {
e.printStackTrace()
}
previewView
}
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment