2

I'm working with a linear gradient background color in compose. I want it to start and stop at a designated portion of the screen but currently it's fill-in the whole screen. How can I change it. I need it to start 200px down the screen and have a height of 250px and a width of 350px.

Here's my linear gradient

val gradient = Brush.linearGradient(0.3f to Color.Green,1.0f to Color.Blue,start = Offset(0.0f, 50.0f),end = Offset(0.0f, 100.0f))

    Box(modifier = Modifier.fillMaxSize().background(gradient))`
  • Have a look at Modifier.drawBehind (https://developer.android.com/reference/kotlin/androidx/compose/ui/draw/package-summary#(androidx.compose.ui.Modifier).drawBehind(kotlin.Function1)) where you can simply draw a rectangle with your brush (https://developer.android.com/reference/kotlin/androidx/compose/ui/graphics/drawscope/DrawScope#drawRect(androidx.compose.ui.graphics.Brush,androidx.compose.ui.geometry.Offset,androidx.compose.ui.geometry.Size,kotlin.Float,androidx.compose.ui.graphics.drawscope.DrawStyle,androidx.compose.ui.graphics.ColorFilter,androidx.compose.ui.graphics.BlendMode)) – 2jan222 Mar 23 '22 at 21:33
  • Your requirements can be written like this`Modifier.padding(top = 200.dp).height(250.dp).width(350.dp).background(gradient)`. If you need pixels instead of DP, check out [this answer](https://stackoverflow.com/a/69140083/3585796) – Phil Dukhov Mar 24 '22 at 03:14

2 Answers2

2

You can use drawBehind and draw a rect.

Box(
    modifier = Modifier
        .fillMaxSize()
        .drawBehind {
            drawRect(
                brush = gradient,
                topLeft = Offset(x = 0f, y = 200.dp.toPx()),
                size = Size(250.dp.toPx(), 350.dp.toPx())
            )
        }
) {

}

you have to update LinearGradient offset as well.

Ehsan msz
  • 1,774
  • 2
  • 13
  • 26
0

You can apply a top padding to your Box to "start 200px down the screen":

val gradient = Brush.linearGradient(0.3f to Color.Green,1.0f to Color.Blue,start = Offset(0.0f, 50.0f),end = Offset(0.0f, 100.0f))

val density = LocalDensity.current
val offsetYDp = density.run { 250.toDp() }
val widthDp = density.run { 350.toDp() }
val heightDp = density.run { 250.toDp() }

Box(
    modifier = Modifier
        .padding(top = offsetYDp)
        .height(heightDp)
        .width(widthDp)
        .background(gradient)
)

enter image description here

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841