1

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/

commandiron
  • 226
  • 1
  • 4
  • 13

2 Answers2

1

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

nglauber
  • 9,971
  • 2
  • 44
  • 50
-1

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

Arda Kazancı
  • 3,877
  • 2
  • 16
  • 33
  • Check out [why](https://meta.stackexchange.com/a/8259/794244) link only answers are considered low quality. You can post it simply as a comment or update your answer by adding details. – Pylyp Dukhov Apr 22 '22 at 16:19