swiftui搭建一个水波纹动画效果
概述
详细
一、运行效果
二、项目结构图
三、程序实现 - 过程
1.创建一个项目命名为 canvas
1.1.引入资源文件和颜色
2. 创建一个虚拟文件new group
命名为 view
3. 创建一个文件new file
选择swiftui view
类型 命名为home
code
contentview - 主窗口
//
// contentview.swift
// shared
//
// created by lyh on 2022/8/27.
//
import swiftui
struct contentview: view {
var body: some view {
home()
}
}
struct contentview_previews: previewprovider {
static var previews: some view {
contentview()
}
}
home - 主页
//
// home.swift
// canvas (ios)
//
// created by lyh on 2022/8/28.
//
import swiftui
struct home: view {
@state var toggle = false
var body: some view {
zstack{
// 波形视图…
waveform(color: .cyan.opacity(0.8),amplify: 150,isreversed: false)
waveform(color: toggle ? color.purple : color.cyan .opacity(0.6),amplify: 140,isreversed: true)
vstack{
hstack{
text("wave's")
.font(.largetitle.bold())
spacer()
toggle(ison: $toggle) {
image(systemname: "eyedropper.halffull")
.font(.title2)
}
.togglestyle(.button)
.tint(.purple)
}
}
.padding()
.frame(maxheight:.infinity,alignment: .top)
}
.ignoressafearea(.all,edges: .bottom)
}
}
struct home_previews: previewprovider {
static var previews: some view {
contentview()
}
}
struct waveform : view{
// 自定义颜色…
var color : color
var amplify : cgfloat
// 反向运动
var isreversed : bool
var body: some view {
// 使用时间线视图查看周期更新…
timelineview(.animation){ timeline in
// 画布视图绘制波浪…
canvas{ context,size in
// 获得当前时间……
let timenow = timeline.date.timeintervalsincereferencedate
// 使用当前时间动画波…
let angle = timenow.remainder(dividingby: 2)
// 计算偏移量……
let offset = angle * size.width
// 绘制文本 仅用来测试偏移量幅度
// context.draw(text("\(offset)"), at: cgpoint(x: size.width/2, y: 100))
// 你可以看到它现在切换到屏幕宽度…
// 你可以看到它在-1.5 -1.5 ....之间移动
// ie 3/2 = 1.5
// 如果2表示-1到1 .....
// 移动整个视图…
// 简单易行的波浪动画
context.translateby(x: isreversed ? -offset : offset, y: 0)
// using swiftui path for darwing wave
// 使用swiftui路径绘制波浪
context.fill(getpath(size: size), with: .color(color))
// darwing curve front and back
// so that tranlation will be look like wave animation...
//绘制前后曲线
//这样翻译看起来就像波浪动画…
context.translateby(x: -size.width, y: 0)
context.fill(getpath(size: size), with: .color(color))
context.translateby(x: size.width * 2, y: 0)
context.fill(getpath(size: size), with: .color(color))
}
}
}
func getpath(size:cgsize)->path{
return path{path in
let midheight = size.height / 2
let width = size.width
// 将波浪移动到中心,引导…
path.move(to: cgpoint(x: 0, y: midheight))
// 画曲线……
// 为底
path.addcurve(to: cgpoint(x: width, y: midheight), control1: cgpoint(x: width * 0.4, y: midheight + amplify), control2: cgpoint(x: width * 0.65, y: midheight - amplify))
// 填充底部剩余区域…
path.addline(to: cgpoint(x: width, y: size.height))
path.addline(to: cgpoint(x: 0, y: size.height))
}
}
}
发表评论