https://kotlinlang.org logo
u

Udi Oshi

01/01/2023, 5:54 PM
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

Kirill Grouchnikov

01/01/2023, 8:16 PM
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

andrew

01/02/2023, 1:32 AM
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

Chris Sinco [G]

01/09/2023, 10:06 PM
Thoughts on this being a generic utility for box shadow @Nader Jawad?
a

andrew

01/09/2023, 10:07 PM
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

romainguy

01/09/2023, 10:08 PM
It’s more complicated than this
It’s a mix of not being hardware accelerated/not working depending on the API level
a

andrew

01/09/2023, 10:09 PM
Ah, sounds like lots of caveats to me 😂
r

romainguy

01/09/2023, 10:09 PM
🤏
a

andrew

01/09/2023, 10:11 PM
A dependency matrix could be nice for this
n

Nader Jawad

01/09/2023, 10:35 PM
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
6 Views