ios - 如何使用 Swift 创建 UIButton Pulse 动画?
解决方案
根据您的要求编辑答案:一个非常简单的实现可能是这样的:
class PulsatingButton: UIButton {
let pulseLayer: CAShapeLayer = {
let shape = CAShapeLayer()
shape.strokeColor = UIColor.clear.cgColor
shape.lineWidth = 10
shape.fillColor = UIColor.white.withAlphaComponent(0.3).cgColor
shape.lineCap = .round
return shape
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupShapes()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupShapes()
}
fileprivate func setupShapes() {
setNeedsLayout()
layoutIfNeeded()
let backgroundLayer = CAShapeLayer()
let circularPath = UIBezierPath(arcCenter: self.center, radius: bounds.size.height/2, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: true)
pulseLayer.frame = bounds
pulseLayer.path = circularPath.cgPath
pulseLayer.position = self.center
self.layer.addSublayer(pulseLayer)
backgroundLayer.path = circularPath.cgPath
backgroundLayer.lineWidth = 10
backgroundLayer.fillColor = UIColor.blue.cgColor
backgroundLayer.lineCap = .round
self.layer.addSublayer(backgroundLayer)
}
func pulse() {
let animation = CABasicAnimation(keyPath: "transform.scale")
animation.toValue = 1.2
animation.duration = 1.0
animation.timingFunction = CAMediaTimingFunction(name: .easeOut)
animation.autoreverses = true
animation.repeatCount = .infinity
pulseLayer.add(animation, forKey: "pulsing")
}
}
比在您的视图控制器中viewDidLoad
或您想要的视图控制器中的位置:
let button = PulsatingButton(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
button.center = self.view.center
view.addSubview(button)
button.pulse()
推荐阅读
- sql-server - SQL - 存储/搜索链接到行的列表的最佳方式
- r - 如何使用 quanteda 进行命名实体识别 (NER)?
- linux - 访问共享内存时出现分段错误
- python - 从 Google Vision API OCR 获取直线和对应坐标
- javascript - 'exhaustive-deps' 的警告不断要求完整的 'props' 对象,而不是允许单个 'props' 方法作为依赖项
- apache-spark - Spark中区分大小写的拼花模式合并
- java - 如何使用 Retrofit 发出请求
- node.js - google sheet api v4更新id等于值的行
- postgresql - 使用 SQL,我可以在分组时在一个表中显示总和和部分总和吗?
- python - '读取请求时出现异常','详细信息':'无法解码:java.io.StringReader@1aac9ea'},'状态':'失败'}