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

如何在SwiftUI中实现矩形的动态流动虚线边框效果

SwiftUI 矩形流动虚线动效实现方案

实现原理:不需要通过旋转实现,直接利用 StrokeStyle 自带的 dashPhase 属性即可完成效果。该属性用于控制虚线的起始偏移量,对其做持续线性动画就能实现虚线沿着矩形边缘流动的效果。

完整实现代码如下:

struct ContentView: View {
    // 控制虚线偏移的状态变量
    @State private var dashPhase: CGFloat = 0
    
    var body: some View {
        Rectangle()
            .strokeBorder(style: StrokeStyle(
                lineWidth: 5,
                dash: [10],
                dashPhase: dashPhase
            ))
            .frame(width: 200, height: 200)
            .foregroundColor(Color.blue)
            .onAppear {
                // 启动无限循环的线性动画
                withAnimation(.linear(duration: 1).repeatForever(autoreverses: false)) {
                    // 终值设为虚线单周期总长度的负值,对应逆时针流动;改为正值则顺时针流动
                    dashPhase = -20
                }
            }
    }
}

自定义调整说明:

  • 调整 duration 的数值可以控制流动速度,数值越小流动速度越快
  • 修改 dash 数组的配置可以调整虚线的实线长度、间隔长度,例如 [15,5] 代表15点长的实线、5点长的间隔交替
  • 把 dashPhase 动画终值的正负调换即可改变流动方向

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 01:45:04