Search code examples
androidkotlinandroid-jetpack-composeandroid-jetpack

Jetpack Compose surface add custom shadow


enter image description here

I am trying to develop a custom toolbar in jetpack compose but its shadow is applying to four sides but I want to achieve 3 side shadow(don't needed in top)

Surface(
    shape = RectangleShape,
    color = toolBarBackground(),
    elevation = 12.dp,
) {
    ...
}

I have tried custom shape, but the problem is path must be closed. I have done a simple tick as follows to overcome that but not working(component size itself changing).

private val CustomThreeSideShape = GenericShape { size, _ ->
    moveTo(0f, -100f)
    lineTo(0f, size.height)
    lineTo(size.width, size.height)
    lineTo(size.width, -100f)
    lineTo(0f, -100f)
    close()
}

Solution

  • This is not yet supported, star this issue for updates.

    Meanwhile you can use this hack with Modifier.drawWithContent combined with DrawScope.clipRect:

    val padding = 20.dp
    val density = LocalDensity.current
    Surface(
        shape = RectangleShape,
        color = Color.White,
        elevation = 12.dp,
        modifier = Modifier
            .padding(padding)
            .drawWithContent {
                val paddingPx = with(density) { padding.toPx() }
                clipRect(
                    left = -paddingPx,
                    top = 0f,
                    right = size.width + paddingPx,
                    bottom = size.height + paddingPx
                ) {
                    [email protected]()
                }
            }
    ) {
        Text(
            "Hello",
            modifier = Modifier.padding(10.dp).fillMaxWidth()
        )
    }
    

    Result:

    enter image description here