首页 > 解决方案 > SwiftUI 可变值处的梯度停止位置

问题描述

我正在尝试在 SwiftUI 中制作由 4 个停靠点组成的渐变。我希望将中间两个锚定到特定堆栈的底部。像这样的东西:

我正在尝试做的事情的 Imgur 链接

这是我目前拥有的渐变代码:

LinearGradient(gradient: Gradient(stops: [

//top       Gradient.Stop(color: Color(hue: 0.0, saturation: 0.0, brightness: 0.0, opacity: 0.0), location: 0.0), 

//variable1 Gradient.Stop(color: Color(hue: 0.0, saturation: 0.0, brightness: 0.0, opacity: 0.3), location: 0.30 //<-Variable), 

//variable2 Gradient.Stop(color: Color(hue: 0.0, saturation: 0.0, brightness: 0.0, opacity: 1.0), location: 0.35 //<-Variable), 

//bottom    Gradient.Stop(color: Color(hue: 0.1, saturation: 1.0, brightness: 0.0, opacity: 1.0), location: 1.0)), 

startPoint: UnitPoint.top, endPoint: UnitPoint.bottom)

标签: xcodeuser-interfacevariablesswiftuigradient

解决方案


您可以简单地使用“内容框”的帧大小来确定放置渐变色标的位置。我只是通过一个名为 frameHeight 的变量来做到这一点。

import SwiftUI

struct ContentView: View {
    
    let screenWidth = UIScreen.main.bounds.width
    let screenHeight = UIScreen.main.bounds.height
    var frameHeight = 200
    var body: some View {
        
        let gradient = Gradient(stops: [Gradient.Stop(color: .blue, location: 0.0), 
         Gradient.Stop(color: .white, location: CGFloat(frameHeight)/screenHeight), 
         Gradient.Stop(color: .black, location: CGFloat(frameHeight)/screenHeight + 0.05), 
         Gradient.Stop(color: .black, location: 1.0)])
        VStack{
            
            //Content Box view of frameHeight
            VStack {
                Text("Content Box")
                
            }.frame(width: screenWidth, height: CGFloat(frameHeight))
           
            Spacer()
        }.frame(width: screenWidth, height: screenHeight)
        .background(LinearGradient(gradient: gradient, startPoint: UnitPoint.top, endPoint: UnitPoint.bottom))
        .edgesIgnoringSafeArea(.all)
    }
}

推荐阅读