用于 SwiftUI 的 OKLCH 渐变

这是 SwiftUI 内置的 LinearGradientRadialGradientEllipticalGradientAngularGradient 形状样式的替代品,它利用 OKLCH 颜色混合来创建更具视觉吸引力的渐变。

使用 iOS 17 的 Shader API 实现,因为这似乎是编写具有自定义渲染的形状样式的唯一方法,而无需依赖私有 API。

使用 SPM 安装

dependencies: [
    .package(url: "https://github.com/fwrs/OKLCHGradient.git", .upToNextMajor(from: "1.0.8"))
]

要使用,只需将 OKLCH 添加到渐变结构名称的前面

// change

Rectangle()
    .background(LinearGradient(
        colors: [.blue, .yellow],
        startPoint: .leading,
        endPoint: .trailing
    ))

// to

import OKLCHGradient

Rectangle()
    .background(OKLCHLinearGradient(
        colors: [.blue, .yellow],
        startPoint: .leading,
        endPoint: .trailing
    ))

然后享受差异

Screenshot comparing a regular SwiftUI gradient to an OKLCH gradient. The regular gradient utilizes a grey color as an intermediate between blue and yellow colors, while OKLCH uses green, which is the color positioned between blue and yellow on a standard color wheel.

注意

目前,无法将 AnyGradient 结构传递给 OKLCH 渐变,因为没有办法使用公共 API 从 AnyGradient 读取颜色停止点。 此功能仅限于 Apple 自己的内置渐变。