How can I create a shape and change its alpha in a specific place on a surface?

Viewed 169

Let's say i have a surface and my background color is Red;

Surface(modifier = Modifier.fillMaxSize().alpha(0.1f)){}

How can i create a shape (example: Rectangle) on surface like hole so i can see the background color not with alpha 0.1f, with alpha 1.0f from inside this rectangle shape?

i want it for tutorial screen in my app, i am open to any idea except my example.

Example of my goal; https://id.pinterest.com/pin/353814114449134862/

2 Answers

I implemented a sample which can give you a kick-off in your implementation:

@Composable
fun CanvasWithHole(
    holeXPosition: Float,
    holeYPosition: Float,
    holeRadius: Float
) {
    androidx.compose.foundation.Canvas(
        modifier = Modifier.fillMaxSize(),
        onDraw = {
            drawIntoCanvas { canvas ->
                val w = drawContext.size.width
                val h = drawContext.size.height
                drawImageWithHole(
                    canvas.nativeCanvas,
                    w, h, holeXPosition, holeYPosition, holeRadius,
                )
            }
        }
    )
}

fun drawImageWithHole(
    canvas: Canvas,
    w: Float,
    h: Float,
    holeXPosition: Float,
    holeYPosition: Float,
    holeRadius: Float
) {
    val bitmap = Bitmap.createBitmap(
        w.toInt(), h.toInt(), Bitmap.Config.ARGB_8888
    ).apply {
        eraseColor(Color.TRANSPARENT)
    }
    val canvasBitmap = Canvas(bitmap)
    val eraser = Paint().apply {
        color = Color.TRANSPARENT
        xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
    }
    canvasBitmap.drawColor(Color.parseColor("#cc328fa8"))
    canvasBitmap.drawCircle(holeXPosition, holeYPosition, holeRadius, eraser)

    canvas.drawBitmap(bitmap, 0f, 0f, null)
}

And here is how you can use it:

@Composable
fun MyScreen() {
    Box {
        ContentScreen()
        CanvasWithHole(
            100f,
            100f,
            400f,
        )
    }
}

Here's the result:

enter image description here

All kinds of materials that will meet your needs are actually in this project. It may be your choice to use and examine the codes.

Library

Related