SwiftUI Widget iOS 14渐变问题

问题描述

我想使用自定义颜色为我的小部件创建渐变颜色。当我仅使用两种颜色时,我遇到了一个问题,结果是没有应用任何一种颜色,而是背景变成了绿色!

struct WeatherWidgetMediumView: View {
    
    var gradient: LinearGradient {
        LinearGradient(
            gradient: Gradient(
                colors:
                [
                    Color(red: 96.0/255.0,green: 171.0/255.0,blue: 239.0/255.0),Color(red: 163.0/255.0,green: 230.0/255.0,blue: 244.0/255.0)
                ]),startPoint: .top,endPoint: .bottom)
    }
    
    var body: some View {
        GeometryReader { geo in
            HStack(alignment: .center) {
                Divider().background(Color.black).padding(.vertical,16.0).opacity(0.1)
            }
        }
        .background(gradient)
    }
}

enter image description here

但是,如果我再添加一种颜色,它看起来很棒。

struct WeatherWidgetMediumView: View {
    let weather: Weather
    
    var gradient: LinearGradient {
        LinearGradient(
            gradient: Gradient(
                colors:
                [
                    Color(red: 96.0/255.0,Color(red: 96.0/255.0,16.0).opacity(0.1)
            }
            Spacer()
        }
        .background(gradient)
    }
}

enter image description here

UPD:创建带有此问题的GitHub项目

https://github.com/Maxim-Zakopaylov/widgetKitGradientIssue

解决方法

我在我的应用程序中遇到了确切的问题,我通过在背景修饰符之后添加 .blendMode(.darken) 来修复它。我希望这也能解决您的问题。

,

此代码显示了使用 iOS 14 的 Widgets 扩展时发生的渐变色错误

LinearGradient(gradient: Gradient(colors: [ Color(red: 0,green: 0.569,blue: 0.945),Color(red: 0,green: 0.329,blue: 0.953)]),startPoint: .top,endPoint: .bottom)

此外,所有三种渐变类型都符合 ShapeStyle 协议,您可以将它们用于背景、填充和描边。例如,这使用我们的彩虹锥形渐变作为圆形的粗内笔画:

Circle()
    .strokeBorder(
        AngularGradient(gradient: Gradient(colors: [.red,.yellow,.green,.blue,.purple,.red]),center: .center,startAngle: .zero,endAngle: .degrees(360)),lineWidth: 50
    )
    .frame(width: 200,height: 200)