Home > Mobile >  How can I only capture the image which is shown inside the box in android jetpack compose?
How can I only capture the image which is shown inside the box in android jetpack compose?

Time:08-31

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.

enter image description here

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     
                 
                })

CodePudding user response:

You'll have to manually crop the Bitmap after capture.

Bitmap.createBitmap(
  source = originalBitmap,
  x = rect.topLeft.x,
  y = rect.topLeft.y,
  width = newWidth,
  height = newHeight
)

CodePudding user response:

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

androidx.compose.ui.graphics.Canvas

And pass your Image as

    val canvas: androidx.compose.ui.graphics.Canvas = Canvas(imageBitmap)

and

canvas.apply {
        drawRoundedRect(
           // properties
            paint = paint
        )
    }

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, NativeCanvasSample2is very similar to what you wish to achieve except what i want to achieve is a cropper gestures.

  • Related