简体   繁体   English

是否可以在 SwiftUI 渐变中向 colors 添加“权重”?

[英]Is it possible to add "Weights" to the colors in a SwiftUI Gradient?

I am using a color gradient as the background for my app (in SwiftUI).我正在使用颜色渐变作为我的应用程序的背景(在 SwiftUI 中)。 它超级简单,看起来像这样

To do this, I have just set the background to a linear color gradient like this (abbreviated):为此,我刚刚将背景设置为这样的线性颜色渐变(缩写):

private var grade = Gradient(colors: [Color("Red"), Color("Blue")])

... ...

.background(LinearGradient(gradient: grade, startPoint: .top, endPoint: .bottom))

I want the gradient to be 'red-shifted' when the user increases the number in the circle (by dragging the little circle), and be 'blue-shifted' when it is a lower number.当用户增加圆圈中的数字(通过拖动小圆圈)时,我希望渐变为“红移”,而当它为较小的数字时,渐变为“蓝移”。

One thing I have tried is setting the colors to a very large array, starting with half being Color("Red"), and half Color("Blue");我尝试过的一件事是将 colors 设置为一个非常大的数组,从一半颜色(“红色”)和一半颜色(“蓝色”)开始; then I thought I could change the number of red as the user drags;然后我想我可以在用户拖动时更改红色的数量; however, this also decreases the amount of gradient applied (it looks much more like a red box and a blue box then a gradient).但是,这也会减少应用的渐变量(它看起来更像是一个红色框和一个蓝色框,然后是渐变)。 It does work on a smaller scale though, so I set the colors to [Color("Red"), Color("Red"), Color("Blue")] to show what I might want it to look like at a larger number:虽然它确实在较小的范围内工作,所以我将 colors 设置为 [Color("Red"), Color("Red"), Color("Blue")] 以显示我可能希望它看起来像更大数字:

在此处输入图像描述

I would like this effect to be continuous (or effectively continuous) though.不过,我希望这种效果是连续的(或有效连续的)。

I hope this demonstrates what I am trying to achieve, and as always, thanks for the help!我希望这能证明我正在努力实现的目标,并且一如既往地感谢您的帮助!

Here is possible solution.这是可能的解决方案。 Tested with Xcode 11.4 / iOS 13.4使用 Xcode 11.4 / iOS 13.4 测试

Note: of course parameters can be modified for your needs注意:当然参数可以根据您的需要进行修改

演示

struct DemoGradientShift: View {
    private var grade = Gradient(colors: [.red, .blue])
    @State private var value: CGFloat = 50
    var body: some View {
        ZStack {
            VStack {
                Rectangle().fill(Color.red)
                Rectangle().fill(Color.blue)
            }
            Rectangle().fill(LinearGradient(gradient: grade, startPoint: .top, endPoint: .bottom))
                .offset(x: 0, y: 5 * (50 - value))
            Slider(value: $value, in: 1...100)
        }
        .edgesIgnoringSafeArea(.all)
    }
}

backup 备份

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

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