0

I am trying to create pulse animation for mic UIButton. Whenever a user clicks the UIButton I am showing pause button meanwhile I need to show pulse animation.

Exactly expecting Like below sample image:

enter image description here

enter image description here

Lin Du
  • 88,126
  • 95
  • 281
  • 483
jackios
  • 155
  • 2
  • 11

1 Answers1

3

Edited answer after your requests: a very, very simple implementation could be this:

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")
}
}

then in your viewDidLoad or where you want inside your View Controller:

let button = PulsatingButton(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
    button.center = self.view.center
    
    view.addSubview(button)
    button.pulse()
Alastar
  • 1,284
  • 1
  • 8
  • 14