JetPack Compose 使背景颜色仅填充屏幕的一部分

发布于 2025-01-16 20:25:14 字数 341 浏览 4 评论 0原文

我正在撰写中使用线性渐变背景颜色。我希望它在屏幕的指定部分开始和停止,但目前它填满了整个屏幕。我该如何改变它。我需要它从屏幕下方 200 像素开始,高度为 250 像素,宽度为 350 像素。

这是我的线性渐变

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))`

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))`

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一抹苦笑 2025-01-23 20:25:14

您可以使用drawBehind并绘制一个矩形。

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

}

您还必须更新 LinearGradient 偏移量。

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.

回忆追雨的时光 2025-01-23 20:25:14

您可以在 Box 上应用顶部填充,以“从屏幕下方 200 像素开始”:

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)
)

在此处输入图像描述

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文