1.使用Rectangle()绘制
struct ContentView: View {
var body: some View {
Rectangle()
.strokeBorder(style: StrokeStyle(lineWidth: 4, dash: [10]))
}
}
在dash参数中使用[10]意味着SwiftUI将绘制10个笔划点,然后再绘制10个点的间距 它是一个数组,因为您可以提供多个值,例如[10,5],表示“10个笔划点,然后是5个点间距
2.给虚线做动画
struct ContentView: View {
@State private var phase: CGFloat = 0
var body: some View {
Rectangle()
.strokeBorder(style: StrokeStyle(lineWidth: 4, dash: [10], dashPhase: phase))
.frame(width: 200, height: 200)
.onAppear {
withAnimation(.linear.repeatForever(autoreverses: false)) {
phase -= 20
}
}
}
}
原文:https://www.hackingwithswift.com/quick-start/swiftui/how-to-create-a-marching-ants-border-effect