自己最近写SwiftApp涉及到的一个知识点, 用于录音界面效果, 平时工作也是写业务逻辑比较多, 简单写一下, 共同学习
实现效果.gif首先自定义一个容器, 方便多处使用
import UIKit
class CVLayerView: UIView {
var pulseLayer : CAShapeLayer! //定义图层
override init(frame: CGRect) {
super.init(frame: frame)
let width = self.bounds.size.width
// 动画图层
pulseLayer = CAShapeLayer()
pulseLayer.bounds = CGRect(x: 0, y: 0, width: width, height: width)
pulseLayer.position = CGPoint(x: width/2, y: width/2)
pulseLayer.backgroundColor = UIColor.clear.cgColor
// 用BezierPath画一个原型
pulseLayer.path = UIBezierPath(ovalIn: pulseLayer.bounds).cgPath
// 脉冲效果的颜色 (注释*1)
pulseLayer.fillColor = #colorLiteral(red: 0.3490196078, green: 0.737254902, blue: 0.8039215686, alpha: 1).cgColor
pulseLayer.opacity = 0.0
// 关键代码
let replicatorLayer = CAReplicatorLayer()
replicatorLayer.bounds = CGRect(x: 0, y: 0, width: width, height: width)
replicatorLayer.position = CGPoint(x: width/2, y: width/2)
replicatorLayer.instanceCount = 3 // 三个复制图层
replicatorLayer.instanceDelay = 1 // 频率
replicatorLayer.addSublayer(pulseLayer)
self.layer.addSublayer(replicatorLayer)
self.layer.insertSublayer(replicatorLayer, at: 0)
}
添加动画
func starAnimation() {
// 透明
let opacityAnimation = CABasicAnimation(keyPath: "opacity")
opacityAnimation.fromValue = 1.0 // 起始值
opacityAnimation.toValue = 0 // 结束值
// 扩散动画
let scaleAnimation = CABasicAnimation(keyPath: "transform")
let t = CATransform3DIdentity
scaleAnimation.fromValue = NSValue(caTransform3D: CATransform3DScale(t, 0.0, 0.0, 0.0))
scaleAnimation.toValue = NSValue(caTransform3D: CATransform3DScale(t, 1.0, 1.0, 0.0))
// 给CAShapeLayer添加组合动画
let groupAnimation = CAAnimationGroup()
groupAnimation.animations = [opacityAnimation,scaleAnimation]
groupAnimation.duration = 3 //持续时间
groupAnimation.autoreverses = false //循环效果
groupAnimation.repeatCount = HUGE
pulseLayer.add(groupAnimation, forKey: nil)
}
CATransform3DScale
- public func CATransform3DScale(_ t: CATransform3D, _ sx: CGFloat, _ sy: CGFloat, _ sz: CGFloat) -> CATransform3D
实现以初始位置为基准,在x轴方向上平移x单位,在y轴方向上平移y单位,在z轴方向上平移z单位
注: 当tx为正值时,会向x轴正方向平移,反之,则向x轴负方向平移;
当ty为正值时,会向y轴正方向平移,反之,则向y轴负方向平移;
当tz为正值时,会向z轴正方向平移,反之,则向z轴负方向平移
Autoreverses = true 效果
循环效果.gif结束动画
调用
let demoView = CVLayerView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_WIDTH))
demoView.center = addBtn.center
// 因为我的VC是XIB 所以将图层添加在到按钮之下 一般用法就直接addSubview就可以了
self.view.insertSubview(demoView, belowSubview: addBtn)
demoView.starAnimation() // 开始动画
后续会持续更新, 根据麦克风声波的频率调整脉冲频率
参考链接
注释*1: http://www.cocoachina.com/ios/20161031/17888.html?utm_source=tuicool&utm_medium=referral
效果来源: https://dribbble.com/shots/3288274-Voice-Recording-App#
OC版 : https://github.com/xiaochaofeiyu/YSCAnimation
网友评论