SwiftUI:渐变填充未显示

SwiftUI: Gradient fill not showing up

以下代码生成一个 Rectangle() 白色且未填充的。我对原因一无所知,而且我没有收到任何错误。

注意: 当我用 Color.redColor.blue 等内置颜色替换自定义颜色时(即 Color(red: green: blue:),填充出现并被着色。

var body: some View {
        Rectangle()
            .fill(
                LinearGradient(
                    colors: [Color(red: 180, green: 40, blue: 55),
                             Color(red: 200, green: 40, blue: 55)],
                    startPoint: .top,
                    endPoint: .bottom)
            )
    }

是什么导致填充不显示,如何在保持自定义颜色的同时解决此问题?

您正在使用的 Color 初始值设定项使用 sRGB 颜色 space 定义颜色,并将任何提供的组件值限制在 0 和 1 之间。因此为所有三个提供大于 1 的任何值values 将创建白色 - 相当于 Color(red: 1.0, green: 1.0, blue: 1.0).

要获得您需要的颜色,您应该将每个值除以 255,例如:

colors: [Color(red: 0.706, green: 0.157, blue: 0.216),
         Color(red: 0.784, green: 0.157, blue: 0.216)],

参见Apple documentation