https://kotlinlang.org logo
#compose
Title
# compose
d

Dan Peluso

01/19/2023, 8:26 PM
Is there a way to add a shadow to a component but only on one side? I know there's the .shadow Modifier extension but I'm looking for one that can add a shadow to only the bottom edge
m

mgrazianodecastro

01/19/2023, 8:27 PM
try this:
Copy code
fun Modifier.advancedShadow(
    color: Color = Color.Black,
    alpha: Float = 0f,
    cornersRadius: Dp = 0.dp,
    shadowBlurRadius: Dp = 0.dp,
    offsetY: Dp = 0.dp,
    offsetX: Dp = 0.dp
) = drawBehind {

    val shadowColor = color.copy(alpha = alpha).toArgb()
    val transparentColor = color.copy(alpha = 0f).toArgb()

    drawIntoCanvas {
        val paint = Paint()
        val frameworkPaint = paint.asFrameworkPaint()

        frameworkPaint.color = transparentColor
        frameworkPaint.setShadowLayer(
            shadowBlurRadius.toPx(),
            offsetX.toPx(),
            offsetY.toPx(),
            shadowColor
        )

        it.drawRoundRect(
            0f,
            0f,
            this.size.width,
            this.size.height,
            cornersRadius.toPx(),
            cornersRadius.toPx(),
            paint
        )
    }
}
I got this solution in this channel, I don't remember quite from who
r

romainguy

01/19/2023, 8:33 PM
It will only work from API 29
m

mgrazianodecastro

01/19/2023, 8:34 PM
yep, the boss knows best /\
d

Dan Peluso

01/19/2023, 8:56 PM
Thanks folks! Unfortunately we have a lower API level than that so looks like I need to keep searching lol
r

romainguy

01/19/2023, 9:44 PM
You could use software rendering to generate the shadow in a bitmap
Or you could use a 9 patch
Or depending on the shape that casts the shadow you could use gradients
26 Views