SwiftUI RoundedRectangle 使用虚线

12 min read

在SwiftUI中,我们可以使用RoundedRectangle来绘制矩形,并将其样式设置为虚线。

要创建一个具有虚线边框的RoundedRectangle,您可以使用以下代码:

struct DashedRoundedRectangle: View {
    var body: some View {
        RoundedRectangle(cornerRadius: 10)
            .stroke(style: StrokeStyle(lineWidth: 2, dash: [5]))
    }
}

在上述代码中,我们首先创建了一个RoundedRectangle,并将其cornerRadius设置为10。然后,我们使用.stroke()方法为矩形添加边框样式。

.stroke()中,我们通过StrokeStyle结构体来定制边框的样式。在这里,我们将lineWidth设置为2,以定义边框的宽度,并使用dash数组来定义虚线的模式。这里的[5]表示虚线中实线和空白之间的间距为5。

最后,只需将DashedRoundedRectangle视图添加到父视图中即可看到具有虚线边框的圆角矩形。

struct ContentView: View {
    var body: some View {
        VStack {
            DashedRoundedRectangle()
                .frame(width: 200, height: 100)
        }
    }
}

请记住,在iOS 13及更高版本上可用的SwiftUI版本中,RoundedRectangle的虚线样式可能仅在模拟器或设备运行时才能看到效果。如果在预览中无法看到虚线效果,请尝试在模拟器或设备上运行您的应用程序。