我正在SwiftUI中创建一个自定义路径,并用红色填充它,我想给路径添加边框或笔触。我们该怎么做?
struct ContentView: View
{
var body: some View
{
Path { path in
path.addArc(center: CGPoint(x: 100, y: 300), radius: 200, startAngle: Angle(degrees: -90), endAngle: Angle(degrees: 0), clockwise: false)
}
.fill(Color.red)
}
}
答案 0 :(得分:1)
首先从声明自定义Shape
开始。您只需要实现func path(in rect: CGRect) -> Path
即可:
struct Diamond: Shape {
func path(in rect: CGRect) -> Path {
let topMid = CGPoint(x: rect.midX, y: rect.minY)
let trailingMid = CGPoint(x: rect.maxX, y: rect.midY)
let bottomMid = CGPoint(x: rect.midX, y: rect.maxY)
let leadingMid = CGPoint(x: rect.minX, y: rect.midY)
var path = Path()
path.move(to: topMid)
path.addLine(to: trailingMid)
path.addLine(to: bottomMid)
path.addLine(to: leadingMid)
path.addLine(to: topMid)
return path
}
}
然后您可以放置在ZStack
中:将背景剪裁到您的自定义形状,并应用描边的自定义形状:
struct ContentView: View {
var body: some View {
ZStack {
Color.blue
.clipShape(Diamond())
Diamond()
.stroke(Color.purple, lineWidth: 4)
} .padding()
}
}
答案 1 :(得分:1)
您需要分别笔触和填充路径。这是一种方法。
将路径分配给变量,然后使用该路径填充变量,然后使用相同的路径覆盖它。注意:您需要使用path.closeSubpath()
来封闭路径,否则只会画出弧。
struct ContentView: View
{
var body: some View {
let path = Path { path in
path.addArc(center: CGPoint(x: 100, y: 300), radius: 200, startAngle: Angle(degrees: -90), endAngle: Angle(degrees: 0), clockwise: false)
path.closeSubpath()
}
path.fill(Color.red).overlay(path.stroke(Color.black, lineWidth: 2))
}
}