思路:
- 获取点击的位置
- 以点击的位置为中心画圆
- 添加定时器,定时让圆的半径增长
- 重绘圆
import UIKit
import CoreGraphics
class CustomButton: UIButton {
// 波纹半径
var viewRadius: CGFloat = 0
// 定时器
var timer: Timer?
// 点击位置的 x 坐标
var circleCenterX: CGFloat = 0
// 点击位置的 y 坐标
var circleCenterY: CGFloat = 0
// 波纹动画的颜色
var targetAnimColor: UIColor = UIColor(red: 216/255.0, green: 114/255.0, blue: 213/255.0, alpha: 0.8)
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor(red: 50/255.0, green: 185/255.0, blue: 170/255.0, alpha: 1.0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// 获取点击位置,初始化定时器
func startButtonAnimation(_ msenderBtn: UIButton, mevent: UIEvent) {
// 动画期间禁止交互
self.isUserInteractionEnabled = false
let button: UIView = msenderBtn as UIView
// 时间的触摸位置的集合
let touchSet: NSSet = mevent.touches(for: button)! as NSSet
var touchArray:[AnyObject] = touchSet.allObjects as [AnyObject]
let touch1: UITouch = touchArray[0] as! UITouch
let point1: CGPoint = touch1.location(in: button)
self.circleCenterX = point1.x
self.circleCenterY = point1.y
// 初始化定时器
timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(timeaction), userInfo: nil, repeats: true)
RunLoop.main.add(timer!, forMode: .commonModes)
}
// 定制器事件
func timeaction() {
// 半径
self.viewRadius += 5
// 重绘
self.setNeedsDisplay()
if viewRadius > bounds.size.width * 0.5 {
viewRadius = 0
timer?.invalidate()
// 取消波纹
self.viewRadius = 0
self.setNeedsDisplay()
// 交互恢复
self.isUserInteractionEnabled = true
}
}
// 重绘波纹
override func draw(_ rect: CGRect) {
let ctx: CGContext = UIGraphicsGetCurrentContext()!
let endangle = Double.pi * 2
// 绘制圆
ctx.addArc(center:CGPoint(x: circleCenterX, y: circleCenterY) , radius: viewRadius, startAngle: 0, endAngle: CGFloat(endangle), clockwise: false)
let stockColor: UIColor = targetAnimColor
stockColor.setStroke()
// 填充颜色
stockColor.setFill()
ctx.fillPath()
}
}
效果图: