如何在 SwiftUI 中制作移动/实时虚线?

use*_*ser 1 swift swiftui

我有这个矩形,我想给它带来移动的破折号效果!如果形状是圆形,我可以简单地用动画旋转视图,因为这是一个矩形!我没有其他想法可以实现这一目标!

struct ContentView: View {
    
    var body: some View {
        
        Rectangle()
            .strokeBorder(style: StrokeStyle(lineWidth: 5, dash: [10]))
            .frame(width: 200, height: 200)
            .foregroundColor(Color.blue)
        
    }
    
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

rob*_*off 6

这有时称为 \xe2\x80\x9carching ants\xe2\x80\x9d 效果。

\n

dashPhase对 的属性进行动画处理StrokeStyle。您希望相位从 0 到虚线图案的总长度。由于您仅在破折号图案中提供了一个值,因此该值将用于部件上和部件外。所以模式的总长度是 10 + 10 = 20。

\n
struct ContentView: View {\n    @State var phase: CGFloat = 0\n    \n    var body: some View {\n        Rectangle()\n            .strokeBorder(\n                style: StrokeStyle(\n                    lineWidth: 5,\n                    dash: [10],\n                    dashPhase: phase))\n            .animation(\n                Animation.linear(duration: 1)\n                    .repeatForever(autoreverses: false),\n                value: phase)\n            .frame(width: 200, height: 200)\n            .foregroundColor(Color.blue)\n            .onAppear {\n                phase = 20\n            }\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n