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

caelum19

05/25/2020, 6:11 PM
Copy code
Box(
    modifier = Modifier
        .preferredSize(500.dp, 500.dp)
        .drawBackground(
            HorizontalGradient(
                0.0f to Color.Red,
                0.5f to Color.Green,
                1.0f to Color.Blue,
                startX = Px.Zero,
                endX = 500.dp.toPx()
            )
        )
)
I'd like for a gradient's end to match the parent's width - is there a nicer way to do this?
z

Zach Klippenstein (he/him) [MOD]

05/25/2020, 8:21 PM
You could try
WithConstraints
k

Kazemihabib1996

05/26/2020, 2:23 PM
Copy code
Box(
    modifier = Modifier
        .fillMaxSize() // for example
        .plus(
            object : DrawModifier {
                override fun ContentDrawScope.draw() {
                    drawRect(
                        HorizontalGradient(
                            0.0f to Color.Red,
                            0.5f to Color.Green,
                            1.0f to Color.Blue,
                            startX = Px.Zero,
                            endX = size.width.toDp().toPx()
                        )
                    )
                    drawContent()
                }
            }
        )
)
c

caelum19

05/28/2020, 9:44 PM
Thanks both of you 🙂 this works great:
Copy code
WithConstraints() {
        Box(
            modifier = Modifier
                .preferredSize(500.dp, 500.dp)
                .drawBackground(
                    HorizontalGradient(
                        0.0f to Color.Red,
                        0.3f to Color.Green,
                        1.0f to Color.Blue,
                        startX = Px.Zero,
                        endX = constraints.maxWidth.toPx()
                    )
                )
        ) {
        }
    }
a

Ali Kabiri

08/17/2021, 9:27 AM
Seems like this is deprecated. Does anyone know the alternative? 🙂
found it haha:
Copy code
val gradient = Brush.horizontalGradient(
            colors = listOf(
                startColor,
                endColor
            ),
            startX = 0f,
            endX = size.value * 2.625f * fill
        )

Box(
            modifier = Modifier
                .background(
                    brush = gradient
                )
    ) {}
🎉 1
c

caelum19

08/19/2021, 10:58 AM
What's the deal with the 2.625f ?
2 Views