【问题标题】:How to create UIButton Pulse animation using Swift? [duplicate]如何使用 Swift 创建 UIButton Pulse 动画? [复制]
【发布时间】:2019-09-28 08:15:15
【问题描述】:

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

完全期待像下面的示例图片:

【问题讨论】:

标签: ios swift animation


【解决方案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()

【讨论】:

  • 谢谢@Alastar。我会在这里尝试更新你。
  • 能否请您发布如何为 UIButton @Alastar 添加
  • @jackios 我已经更新了答案,这几乎就是你所需要的
  • 我在故事板中维护我的 UIButton。另外,我需要实现类似雷达脉冲动画。
猜你喜欢
  • 2015-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-05
  • 2011-05-19
  • 1970-01-01
  • 2016-02-17
  • 1970-01-01
相关资源
最近更新 更多