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

这篇博客介绍了如何在iOS应用中使用SwiftUI创建线性渐变和径向渐变背景。通过LinearGradient和RadialGradient结构体,可以实现颜色从一端平滑过渡到另一端的线性效果,以及从中心向外扩散的径向效果。示例代码展示了如何在View和Button上应用这些渐变,并提供了相关Apple开发者文档链接以供参考。
摘要由CSDN通过智能技术生成

iOS 使用渐变色进行填充

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

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

1.线性变化

效果如图:
ps:因颜色有重合部分,所以会生成新的颜色,使用的渐变颜色为:blue,red,yellow
在这里插入图片描述

相应代码

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

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的背景色上进行使用

效果如图:
在这里插入图片描述

相应代码

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

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渐变器来进行径向发散渐变

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开发者文档相应网址:

  • 线性渐变器

https://developer.apple.com/documentation/swiftui/lineargradient/

  • 径向渐变器

https://developer.apple.com/documentation/swiftui/radialgradient/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

淡酒交魂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值