Skip to content

Instantly share code, notes, and snippets.

@jisungbin
Created November 7, 2023 01:52
Show Gist options
  • Save jisungbin/07db48b6fdcbf1fc4c1f150913da9e88 to your computer and use it in GitHub Desktop.
Save jisungbin/07db48b6fdcbf1fc4c1f150913da9e88 to your computer and use it in GitHub Desktop.
JetpackCompose-DropShadow
@Stable
fun Modifier.dropShadow(
borderRadius: Dp,
spreadRadius: Dp = 3.dp,
blurRadius: Dp = spreadRadius,
color: Color = Color.DarkGray.copy(alpha = 0.1f),
offsetX: Dp = 0.dp,
offsetY: Dp = 0.dp,
) =
drawBehind {
drawIntoCanvas { canvas ->
val paint = Paint().also { paint ->
paint.asFrameworkPaint().apply {
this.color = color.toArgb()
if (blurRadius != 0.dp) {
maskFilter = BlurMaskFilter(blurRadius.toPx(), BlurMaskFilter.Blur.NORMAL)
}
}
}
val spreadPixel = spreadRadius.toPx()
val leftPixel = (0f - spreadPixel) + offsetX.toPx()
val topPixel = (0f - spreadPixel) + offsetY.toPx()
val rightPixel = size.width + spreadPixel
val bottomPixel = size.height + spreadPixel
canvas.drawRoundRect(
left = leftPixel,
top = topPixel,
right = rightPixel,
bottom = bottomPixel,
radiusX = borderRadius.toPx(),
radiusY = borderRadius.toPx(),
paint = paint,
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment