在 SwiftUI 中,创建渐变颜色非常简单,使用 LinearGradient、RadialGradient 和 AngularGradient 都能轻松实现不同类型的渐变效果。每种渐变类型都有其独特的效果。
1、Linear Gradient(线性渐变)
线性渐变会在指定的方向上从一个颜色过渡到另一个颜色。
示例:
Text("Linear Gradient")
.font(.title)
.padding()
.foregroundColor(.white)
.background(
LinearGradient(
gradient: Gradient(colors: [.blue, .green]), // 渐变的颜色
startPoint: .topLeading, // 渐变的起始点
endPoint: .bottomTrailing // 渐变的结束点
)
.cornerRadius(10)
)
在这个例子中,渐变从 .topLeading 角落到 .bottomTrailing 角落,颜色从蓝色过渡到绿色。

2、Radial Gradient(径向渐变)
径向渐变是从中心向外扩展的渐变效果,适合用于圆形或有中心点的渐变效果。
示例:
Text("Radial Gradient")
.font(.title)
.padding()
.foregroundColor(.white)
.background(
RadialGradient(
gradient: Gradient(colors: [.yellow, .red]), // 渐变的颜色
center: .center, // 渐变的中心位置
startRadius: 20, // 起始半径
endRadius: 200 // 结束半径
)
.cornerRadius(10)
)
在这个例子中,渐变从文本的中心开始,颜色从黄色到红色逐渐变化。

3、Angular Gradient(角度渐变)
角度渐变是围绕某个点旋转的渐变效果,适合用于圆形或圆弧区域。
示例:
Text("Angular Gradient")
.font(.title)
.padding()
.foregroundColor(.white)
.background(
AngularGradient(
gradient: Gradient(colors: [.purple, .pink, .orange]), // 渐变的颜色
center: .center, // 渐变的中心位置
angle: .degrees(0) // 渐变的起始角度
)
.cornerRadius(10)
)
在这个例子中,渐变颜色围绕中心点进行旋转,颜色从紫色到粉色再到橙色。

4、渐变颜色的更多自定义选项
调整渐变的颜色点:可以通过 Gradient(stops:) 自定义渐变颜色的位置(即每个颜色的停止点)。每个 Gradient.Stop 可以定义颜色和对应的停止点。
自定义渐变停止点
Text("Custom Gradient Stops")
.font(.title)
.padding()
.foregroundColor(.white)
.background(
LinearGradient(
gradient: Gradient(stops: [
.init(color: .red, location: 0.0),
.init(color: .yellow, location: 0.5),
.init(color: .green, location: 1.0)
]),
startPoint: .top,
endPoint: .bottom
)
.cornerRadius(10)
)
在这个例子中,渐变有三个颜色:红色、黄色和绿色。它们分别在渐变的起始、中心和结束位置停留。

5、渐变在图形中的应用
除了文本,还可以在任何视图中使用渐变颜色,例如 Rectangle、Circle、Image 等。
在矩形中应用渐变
Rectangle()
.fill(LinearGradient(gradient: Gradient(colors: [.blue, .green]), startPoint: .top, endPoint: .bottom))
.frame(width: 200, height: 200)
.cornerRadius(20)
在这个例子中,渐变填充了一个矩形,颜色从蓝色渐变到绿色。

总结
LinearGradient:适用于线性渐变,定义渐变的起始和结束点。
RadialGradient:适用于从中心向外扩展的渐变效果。
AngularGradient:适用于围绕中心旋转的渐变效果。
自定义渐变停止点:使用 Gradient(stops:) 可以进一步定制渐变的颜色和位置。