Skip to content

Instantly share code, notes, and snippets.

@hoangchungk53qx1
Last active August 17, 2024 09:13
Show Gist options
  • Save hoangchungk53qx1/b17356cc82515666058b3d53781bf5d5 to your computer and use it in GitHub Desktop.
Save hoangchungk53qx1/b17356cc82515666058b3d53781bf5d5 to your computer and use it in GitHub Desktop.
TestCropImageCompose
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@Composable
fun TestCropImage() {
val context = LocalContext.current
val cropView = remember {
CropImageView(context).apply {
isAutoZoomEnabled = false
cropShape = CropImageView.CropShape.RECTANGLE
setFixedAspectRatio(true)
}
}
var readStoragePermissionGranted by rememberSaveable { mutableStateOf(false) }
val readStoragePermissionLauncher =
rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) {
readStoragePermissionGranted = it
}
val readStoragePermissionRequired = Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q
LaunchedEffect(readStoragePermissionRequired, readStoragePermissionGranted) {
if (readStoragePermissionRequired && !readStoragePermissionGranted) {
readStoragePermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
}
}
Scaffold(
modifier = Modifier.fillMaxSize(),
containerColor = Color.Transparent,
) { padding ->
Row(
Modifier
.fillMaxSize()
.padding(padding)
.consumeWindowInsets(padding)
.windowInsetsPadding(
WindowInsets.safeDrawing.only(
WindowInsetsSides.Horizontal,
),
),
) {
var bitmapImage: Bitmap? by remember { mutableStateOf(null) }
val imagePickerLauncher =
rememberLauncherForActivityResult(contract = ActivityResultContracts.GetContent()) { uri: Uri? ->
uri?.let {
bitmapImage = getBitmapFromUri(context, uri)
cropView.setImageBitmap(bitmapImage)
}
}
LaunchedEffect(Unit) {
imagePickerLauncher.launch("image/*")
}
BoxWithConstraints(Modifier.fillMaxSize()) {
bitmapImage?.let {
Image(
bitmap = it.asImageBitmap(),
contentScale = ContentScale.Crop,
contentDescription = null,
modifier = Modifier.fillMaxSize(),
)
}
val width = with(LocalDensity.current) {
[email protected]()
}
val height = with(LocalDensity.current) {
[email protected]()
}
AndroidView(
factory = {
cropView
},
) {
it.updateLayoutParams {
this.height = height
this.width = width
}
}
}
}
}
}
fun getBitmapFromUri(context: Context, imageUri: Uri): Bitmap {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
@Suppress("DEPRECATION") return MediaStore.Images.Media.getBitmap(
context.contentResolver,
imageUri,
)
} else {
val source = ImageDecoder.createSource(context.contentResolver, imageUri)
return ImageDecoder.decodeBitmap(source)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment