Taking pictures using Jetpack Compose | by Daniel Atitienei - Medium
Grab a cup of coffee ☕ and let's see how can we use Jetpack Compose to take photos directly in the app.
Before starting, let's add the camera permission to the AndroidManifest.xml
file.
<uses-feature
android:name="android.hardware.camera"
android:required="false" /><uses-permission android:name="android.permission.CAMERA" />
Firstly, we need to create a variable to store the bitmap we'll get after taking the photo.
var bitmap by remember {
mutableStateOf<Bitmap?>(null)
}
Now to open the camera we need to use rememberLauncherForActivityResult
that has a TakePicturePreview
contract.
val cameraLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.TakePicturePreview(),
onResult = { newImage ->
bitmap = newImage
}
)
Let's create the permission launcher, which will request camera permission and launch the camera preview if permission is granted.
val permissionLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted ->
if (isGranted) {
cameraLauncher.launch()
}
}
Using The Camera
Let's add an Image
and a TextButton
. The Image
will show up only if the bitmap
is not empty.
Column {
bitmap?.let {
Image(
bitmap = it.asImageBitmap(),
contentDescription = null,
modifier = Modifier
.clip(CircleShape)
.size(36.dp)
)
}val context = LocalContext.current
TextButton(
onClick = {
// Checks if the permission is granted
val permissionCheckResult =
ContextCompat.checkSelfPermission(context, android.Manifest.permission.CAMERA)
if (permissionCheckResult == PackageManager.PERMISSION_GRANTED) {
// The permission is already granted
cameraLauncher.launch()
} else {
// Launches the permission request
cameraPermissionLauncher.launch(android.Manifest.permission.CAMERA)
}
}
) {
Text(
text = "Use camera"
)
}
}
I hope this article has been a valuable part of your development journey. For the latest updates, follow me and subscribe to the newsletter. If you appreciate my content, a coffee would be much appreciated! Thanks for reading! 😊☕️
Comments
Post a Comment