Hello Trying to create a simple ext for Shadow: ``...
# compose
u
Hello Trying to create a simple ext for Shadow:
Copy code
@Composable
fun Shadow.simpleDropShadow(color: Color? = null, offset: Offset?, blurRadius: Float?) = Shadow(
    color = color ?: colorResource(id = R.color.black_75),
    offset = offset ?: Offset(x = 2f, y = 4f),
    blurRadius = blurRadius ?: 0.1f
)
But no luck when trying to use in at all. Appreciate your assitance 🙏
k
You gotta be more specific. Is it not compiling? Does it crash at runtime? Does it not show at all? Does it show incorrect color? What's the compose version? What's the platform you're using and the version of that platform?
a
Copy code
fun Modifier.coloredShadow(
    color: Color,
    shape: Shape,
    alpha: Float = 0.2F,
    shadowRadius: Dp = 0.dp,
    offsetY: Dp = 0.dp,
    offsetX: Dp = 0.dp,
) = coloredShadow(color, shape, alpha, shadowRadius, DpOffset(offsetX, offsetY))

fun Modifier.coloredShadow(
    color: Color,
    shape: Shape,
    alpha: Float = 0.2F,
    shadowRadius: Dp = 0.dp,
    offset: DpOffset = DpOffset(0.dp, 0.dp),
) = composed {
    val density = LocalDensity.current

    val shadowColor = remember(color, alpha) { color.copy(alpha).toArgb() }
    val paint = remember(shadowRadius, offset.x, offset.y, shadowColor, density) { Paint().apply {
        val frameworkPaint = asFrameworkPaint()

        with(density) {
            frameworkPaint.color = Color.Transparent.toArgb()
            frameworkPaint.setShadowLayer(
                shadowRadius.toPx(),
                offset.x.toPx(),
                offset.y.toPx(),
                shadowColor
            )
        }
    }}

    drawBehind {
        drawIntoCanvas {
            it.drawOutline(
                shape.createOutline(size, layoutDirection, this),
                paint
            )
        }
    }
}
c
Thoughts on this being a generic utility for box shadow @Nader Jawad?
a
I think the caveat is older android versions might not be hardware accelerated 🤔
@romainguy had an answer for this a while back, but I can't recall if that was the case
I use it and it works fine though 🙂
r
It’s more complicated than this
It’s a mix of not being hardware accelerated/not working depending on the API level
a
Ah, sounds like lots of caveats to me 😂
r
🤏
a
A dependency matrix could be nice for this
n
Yes in Android versions older than P using Paint#setShadowLayer only works in software rendered pipelines
@andrew there is already a list of hardware accelerated drawing operations on DAC here: https://developer.android.com/topic/performance/hardware-accel#drawing-support