「SwiftUI」Gradient渐变颜色填充效果

iOS 使用渐变色进行填充

这需要使用到Gradient渐变器来实现颜色的渐变变化

常用的有两种:颜色线性变化,径向发散变化

1.线性变化

效果如图:

ps:因颜色有重合部分,所以会生成新的颜色,使用的渐变颜色为:blue,red,yellow

相应代码

使用了LinearGradient渐变器来进行线性发散渐变

swift 复制代码
struct ContentView: View {
    var body: some View {
        LinearGradient(gradient: 
        //需要渐变的颜色,通常两个,此处使用三个表示不是只能使用两种颜色
        Gradient(colors: [.blue,.red, .yellow]),
        //开始渐变的起点
        startPoint: .leading,
        //开始渐变的终点
        endPoint: .trailing)
            .frame(width: 300, height: 100)
    }
}

1.2也可以在Button的背景色上进行使用

效果如图:

相应代码

将线性渐变填充到背景色中,即可完成摁钮的渐变色背景

swift 复制代码
struct ContentView: View {
    var body: some View {
        VStack{
            Text("线性渐变")
                .bold()
                .frame(width: 300, height: 100, alignment: .center)
                .foregroundColor(Color.white)
                .background(LinearGradient(gradient: Gradient(colors: [Color.red,Color.yellow]),
                                           startPoint: .leading,
                                           endPoint: .trailing))
                .clipShape(RoundedRectangle(cornerRadius: 20))
        }
    }
}

2.径向发散变化

效果如图:

相应代码

使用了RadialGradient渐变器来进行径向发散渐变

swift 复制代码
struct ContentView: View {
    var body: some View {
        RadialGradient(gradient:
        				//渐变的颜色,从核心点到四周
                        Gradient(colors: [Color.blue,Color.white.opacity(0)]),
                        //设置发散起点(也就是核心点,通常都为center)
                       center: .center, 
                       //发散起点圆角(半径点)
                       startRadius: 0,
                       //发散结束点半径
                       endRadius: 120)
            .frame(width: 240, height: 240)
    }
}

ps:需要注意的是整个渐变器的frame大小最好设置发散结束半径的两倍左右,否则会出现如下图一样有边框感和分裂感,没有周围完全晕染出来的感觉

错误样式:

Apple开发者文档相应网址:

  • 线性渐变器

developer.apple.com/documentati...

  • 径向渐变器

developer.apple.com/documentati...

相关推荐
汉秋6 小时前
SwiftUI 中的 compositingGroup():真正含义与渲染原理
swiftui·swift
汉秋7 小时前
SwiftUI 中的 @ViewBuilder 全面解析
swiftui·swift
胖虎121 小时前
SwiftUI 页面作为一级页面数据被重置问题分析
ios·swiftui·swift·state·observedobject·stateobject·swiftui页面生命周期
guangzan1 天前
AI 结队编程:解决 SwiftUI 窗口点击关闭按钮崩溃问题
swiftui·tca
1024小神1 天前
xcode 配置了AppIcon 但是不显示icon图标
ios·swiftui·swift
东坡肘子3 天前
周日小插曲 -- 肘子的 Swift 周报 #115
人工智能·swiftui·swift
YungFan4 天前
iOS开发之MetricKit监控App性能
ios·swiftui·swift
1024小神7 天前
xcode 中配置AR Resource Group并设置图片宽度等
ios·swiftui·ar·xcode·swift
lancoff9 天前
#5 ScrollViewReader
ios·swiftui
lancoff9 天前
#6 GeometryReader
ios·swiftui