Issue
I have searched everywhere but didn't got a single documentation about cropping images in Jetpack Compose
How to crop Image in Jetpack Compose?
Solution
You can actually just use those older Android libraries no problem.
I used this one: https://github.com/CanHub/Android-Image-Cropper
Project build.gradle:
allprojects {
repositories {
google()
mavenCentral()
maven(url = "https://jitpack.io")
}
}
App build.gradle:
implementation("com.github.CanHub:Android-Image-Cropper:4.0.0")
Usage (CropImageContract is provided by the above):
@Composable
fun ImageSelectorAndCropper() {
var imageUri by remember {
mutableStateOf<Uri?>(null)
}
val context = LocalContext.current
val bitmap = remember {
mutableStateOf<Bitmap?>(null)
}
val imageCropLauncher = rememberLauncherForActivityResult(CropImageContract()) { result ->
if (result.isSuccessful) {
// use the cropped image
imageUri = result.uriContent
} else {
// an error occurred cropping
val exception = result.error
}
}
val imagePickerLauncher = rememberLauncherForActivityResult(contract = ActivityResultContracts.GetContent()) { uri: Uri? ->
val cropOptions = CropImageContractOptions(uri, CropImageOptions())
imageCropLauncher.launch(cropOptions)
}
if (imageUri != null) {
if (Build.VERSION.SDK_INT < 28) {
bitmap.value = MediaStore.Images.Media.getBitmap(context.contentResolver, imageUri)
} else {
val source = ImageDecoder.createSource(context.contentResolver, imageUri!!)
bitmap.value = ImageDecoder.decodeBitmap(source)
}
Button(onClick = { imagePickerLauncher.launch("image/*") }) {
Text("Pick image to crop")
}
}
}
Edit:
I also had to add this to the manifest so that the CropActivity picks up a theme
<activity android:name="com.canhub.cropper.CropImageActivity"
android:theme="@style/Base.Theme.AppCompat"/>
Answered By - Eric
Answer Checked By - Katrina (JavaFixing Volunteer)