简体   繁体   English

如何在 Jetpack Compose 中创建椭圆渐变

[英]How to create oval gradient in Jetpack Compose

I need oval gradient for a background, but all I'm able to get is perfectly round gradient with Brush.radialGradient(..) :我需要椭圆形渐变作为背景,但我能得到的只是带有Brush.radialGradient(..)的完美圆形渐变:

Modifier
    .fillMaxSize()
    .background(
        brush = Brush.radialGradient(
            colors = listOf(Color(0xFFffffff), Color(0xFF000000)),
        ),
    )

This is what I need (the shape of the oval must of course be aligned with screen size ratio):这就是我需要的(椭圆的形状当然必须与屏幕尺寸比例对齐):

这就是我需要的

But all I am able to produce, is this:但我所能产生的,是这样的:

这是我能够生产的

Any ideas on how can I solve this?关于如何解决这个问题的任何想法?

Radical gradient shouldn't stretch like this, it determine pixel color depending on distance from the center.激进渐变不应该像这样拉伸,它根据与中心的距离确定像素颜色。

I'm not sure why there's no "Oval" gradient, but it's missing from android itself, and compose is just an interlayer here.我不确定为什么没有“椭圆”渐变,但 android 本身就没有它,而 compose 在这里只是一个中间层。

What is usually done in the android is just scaling the view. android 通常所做的只是缩放视图。 You can do it on compose too:您也可以在 compose 上执行此操作:

BoxWithConstraints(
    Modifier
        .fillMaxSize()
) {
    val aspectRatio = maxWidth / maxHeight
    Box(
        Modifier
            .fillMaxSize()
            .scale(maxOf(aspectRatio, 1f), maxOf(1 / aspectRatio, 1f))
            .background(
                brush = Brush.radialGradient(
                    colors = listOf(Color(0xFFffffff), Color(0xFF000000)),
                ),
            )
    )
}

Here I'm using BoxWithConstraints to get maxWidth and maxHeight , in order to calculate needed scale.在这里,我使用BoxWithConstraints来获取maxWidthmaxHeight ,以计算所需的比例。

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM