
🙏 Supported by Emerge Tools
The platform for all your mobile performance needs
Colored Shadow
Author: Arthur Gonzaga
Jetpack Compose ships with a shadow Modifier that makes is really trivial to add a shadow to your Composable. However, shadows in Jetpack Compose do not have the ability to customize their color. This snippet provides a solution to overcome this limitation using Modifiers and the classic Android paint object.
import androidx.compose.ui.Modifier | |
import androidx.compose.ui.composed | |
import androidx.compose.ui.draw.drawBehind | |
import androidx.compose.ui.graphics.Color | |
import androidx.compose.ui.graphics.Paint | |
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas | |
import androidx.compose.ui.graphics.toArgb | |
import androidx.compose.ui.unit.Dp | |
import androidx.compose.ui.unit.dp | |
fun Modifier.coloredShadow( | |
color: Color, | |
alpha: Float = 0.2f, | |
borderRadius: Dp = 0.dp, | |
shadowRadius: Dp = 20.dp, | |
offsetY: Dp = 0.dp, | |
offsetX: Dp = 0.dp | |
) = composed { | |
val shadowColor = color.copy(alpha = alpha).toArgb() | |
val transparent = color.copy(alpha= 0f).toArgb() | |
this.drawBehind { | |
this.drawIntoCanvas { | |
val paint = Paint() | |
val frameworkPaint = paint.asFrameworkPaint() | |
frameworkPaint.color = transparent | |
frameworkPaint.setShadowLayer( | |
shadowRadius.toPx(), | |
offsetX.toPx(), | |
offsetY.toPx(), | |
shadowColor | |
) | |
it.drawRoundRect( | |
0f, | |
0f, | |
this.size.width, | |
this.size.height, | |
borderRadius.toPx(), | |
borderRadius.toPx(), | |
paint | |
) | |
} | |
} | |
} |
Have a project you'd like to submit? Fill this form, will ya!
If you like this snippet, you might also like:
Maker OS is an all-in-one productivity system for developers
I built Maker OS to track, manage & organize my life. Now you can do it too!