如何使用Swift创建UIButton Pulse动画?

时间:2019-05-10 11:59:14

标签: ios swift animation

我正在尝试为麦克风UIButton创建脉冲动画。每当用户单击UIButton时,我都会显示暂停按钮,同时我需要显示脉冲动画。

正像下面的示例图片一样

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

在您的请求后编辑的答案:一个非常非常简单的实现可以是这样:

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中或您要在viewController中的位置要好:

let button = PulsatingButton(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
    button.center = self.view.center

    view.addSubview(button)
    button.pulse()