You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Swift实现的圆形脉冲动画修改为矩形脉冲动画

矩形脉冲动画修改方案

核心修改点在createPulse方法的路径创建和layer属性配置部分,其余动画逻辑无需调整:

具体修改说明

  • 将原来的圆形贝塞尔路径替换为和目标控件binauralBackView尺寸匹配的矩形路径
  • 删除给脉冲层设置圆角半径为宽度一半的代码(该配置是圆形效果的必要配置,矩形无需使用,若需要圆角矩形脉冲可以自行设置合适的圆角值)

修改后的完整代码

createPulse方法

func createPulse() {
    for _ in 0...3 {
        // 替换原来的圆形路径为矩形路径,若需要圆角矩形可使用UIBezierPath(roundedRect: cornerRadius:)
        let rectPath = UIBezierPath(rect: CGRect(
            x: -binauralBackView.bounds.width/2,
            y: -binauralBackView.bounds.height/2,
            width: binauralBackView.bounds.width,
            height: binauralBackView.bounds.height
        ))
        let pulseLayer = CAShapeLayer()
        pulseLayer.path = rectPath.cgPath
        pulseLayer.lineWidth = 2
        pulseLayer.fillColor = UIColor.clear.cgColor
        
        pulseLayer.lineCap = CAShapeLayerLineCap.round
        pulseLayer.position = CGPoint(x: binauralBackView.frame.size.width/2, y: binauralBackView.frame.size.height/2)
        // 删掉原来的cornerRadius赋值,若要圆角可设置为你需要的数值,比如 pulseLayer.cornerRadius = 8
        binauralBackView.layer.insertSublayer(pulseLayer, at: 0)
        pulseLayers.append(pulseLayer)
    }
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
        self.animatePulse(index: 0)
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
            self.animatePulse(index: 1)
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                self.animatePulse(index: 2)
            }
        }
    }
}

animatePulse方法

原有逻辑完全不需要修改,直接沿用即可。

可选扩展

如果需要实现带圆角的矩形脉冲,只需要把路径创建部分替换为如下代码即可,可自行调整cornerRadius参数控制圆角大小:

let rectPath = UIBezierPath(roundedRect: CGRect(
    x: -binauralBackView.bounds.width/2,
    y: -binauralBackView.bounds.height/2,
    width: binauralBackView.bounds.width,
    height: binauralBackView.bounds.height
), cornerRadius: 8)

内容的提问来源于stack exchange,提问作者Oleg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 10:18:01