How can I only capture the image which is shown inside the box in this camera overlay. I am able to get the bitmap of the image successfully.
I can get the position of the box by this
Image(painter = painterResource(id = R.drawable.ic_background_round),
contentDescription = null,
modifier = Modifier.onGloballyPositioned { coordinates ->
val rect = coordinates.boundsInRoot()
rectTopLeft = rect.topLeft
rectBottomRight = rect.bottomRight
})
2
Answers
You’ll have to manually crop the
Bitmap
after capture.Creating a new bitmap will return a portion of original image in Rectangle shape not in a custom shape. Very likely reason you get that exception is difference between Composable and Bitmap dimensions. When you crop an image on a Composable you need to interpolate left and size of Composable to Bitmap left and size.
What this means is let’s say your image is 1000x1000px while your screen is 2000x2000px
if you wish to get (200,200) position with 1000px width/height on Composable you get it as
val actualLeft =left* (bitmapWidth/composableWidth)
200*(1000/2000) = 100 should be the coordinate of left position on image. Same goes for y coordinate, width and height.
What you actually ask is image cropper with shape minus gestures. As i answered in previous question you need to use Canvas. But this time Canvas should be
And pass your Image as
and
then draw the shape, and convert it to a path since we need to use it in this Canvas with a Paint. This Paint should have XferMode.SrcIn. I will update this answer when i’m available. You can check out this question,
NativeCanvasSample2
is very similar to what you wish to achieve except what i want to achieve is a cropper gestures.I made a workaround and sample that how you can clip with a shape
SrcIn
with compose Canvas or using scaling and interpolation to correctly clip an image usingrectDraw
andrectCrop
.Usage
Dialog
Result
In result the one in screen is due to
BlendMode.SrcIn
if you fusion with the Canvas that takes image you will be able to get it. The one in dialog is the actual one because of cropping image. As i mentioned above you can crop images with a Rectangle.You need to implement Canvas(bitmap) for custom shapes as in my question, i might update this answer with
androidx.compose.ui.graphics.Canvas = Canvas(imageBitmap)
when i’m available in the future, i faced some issues but will fix them soon. This is basically how to build an image cropper with shape and crop after scaling in Bitmap dimensions.