思路:
- 獲取點(diǎn)擊的位置
- 以點(diǎn)擊的位置為中心畫圓
- 添加定時(shí)器,定時(shí)讓圓的半徑增長(zhǎng)
- 重繪圓
import UIKit
import CoreGraphics
class CustomButton: UIButton {
// 波紋半徑
var viewRadius: CGFloat = 0
// 定時(shí)器
var timer: Timer?
// 點(diǎn)擊位置的 x 坐標(biāo)
var circleCenterX: CGFloat = 0
// 點(diǎn)擊位置的 y 坐標(biāo)
var circleCenterY: CGFloat = 0
// 波紋動(dòng)畫的顏色
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")
}
// 獲取點(diǎn)擊位置,初始化定時(shí)器
func startButtonAnimation(_ msenderBtn: UIButton, mevent: UIEvent) {
// 動(dòng)畫期間禁止交互
self.isUserInteractionEnabled = false
let button: UIView = msenderBtn as UIView
// 時(shí)間的觸摸位置的集合
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
// 初始化定時(shí)器
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()
// 交互恢復(fù)
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()
}
}
效果圖: