SwiftUI为我们提供了三种可以使用的渐变,就像颜色一样,它们也是可以在我们的UI中绘制的视图。
渐变由以下几部分组成:
- 要显示的颜色数组
- 尺寸和方向信息
- 要使用的渐变类型
例如,线性渐变 LinearGradient
沿一个方向运行,因此我们为其提供了一个起点和终点,如下所示:
LinearGradient(gradient: Gradient(colors: [.white, .black]), startPoint: .top, endPoint: .bottom)
在内部的Gradient
类型可以提供渐变色标,让您既可以指定颜色,也可以指定沿渐变应使用的距离。
相比之下,径向渐变 RadialGradient
以圆形向外移动,因此,我们没有指定方向,而是指定了起点和终点半径——颜色应从圆心到圆心的距离开始和停止变化。例如:
RadialGradient(gradient: Gradient(colors: [.blue, .black]), center: .center, startRadius: 20, endRadius: 200)
最后一种渐变类型称为角度渐变 AngularGradient
,尽管您可能听说过其他地方将其称为圆锥形或圆锥形渐变。这使颜色围绕一个圆圈循环而不是向外辐射,并且可以创建一些美丽的效果。
例如,这将以渐变的中心为中心在单个渐变中循环显示一系列颜色:
AngularGradient(gradient: Gradient(colors: [.red, .yellow, .green, .blue, .purple, .red]), center: .center)
所有这些渐变都可以单独用作视图,也可以用作修改器的一部分。例如,您可以将它们用作文本视图的背景。
附:
使用如下示例代码:
struct ContentView: View {
var body: some View {
VStack {
LinearGradient(gradient: Gradient(colors: [.white, .black]), startPoint: .leading, endPoint: .trailing)
RadialGradient(gradient: Gradient(colors: [.blue, .black]), center: .center, startRadius: 20, endRadius: 200)
AngularGradient(gradient: Gradient(colors: [.red, .yellow, .green, .blue, .purple, .red]), center: .center)
}
}
}
得到如下结果:

Previous: 颜色和视图位置 | Next: 按钮和图片 |
---|
赏我一个赞吧~~~
网友评论