我的代码存在一个问题,即 strokeBorder 没有在 Border 内描边,如果我对 Shape 使用填充,它会保留并尊重边框,但 strokeBorder 却不会这样做,如何解决这个问题?
import SwiftUI
struct ContentView: View {
var body: some View {
let myCustomInsettableShape = TestShape()
ZStack {
myCustomInsettableShape
.fill(Color.white)
myCustomInsettableShape
.strokeBorder(Color.black.opacity(0.5), style: StrokeStyle(lineWidth: 50.0, lineCap: .round, lineJoin: .miter))
}
.background(Color.red)
.padding(50)
}
}
struct TestShape: InsettableShape {
var insetAmount: CGFloat = .zero
func path(in rect: CGRect) -> Path {
// Adjust the rect to account for half the stroke width to ensure it stays inside
let insetRect = rect.insetBy(dx: insetAmount, dy: insetAmount)
// Create the path for the shape
return Path { path in
path.move(to: CGPoint(x: insetRect.minX, y: insetRect.midY))
path.addLine(to: CGPoint(x: insetRect.midX, y: insetRect.minY))
path.addLine(to: CGPoint(x: insetRect.maxX, y: insetRect.midY))
path.addLine(to: CGPoint(x: insetRect.midX, y: insetRect.maxY))
path.closeSubpath()
}
}
func inset(by amount: CGFloat) -> some InsettableShape {
var myShape = self
myShape.insetAmount += amount
return myShape
}
}
当您使用时
.strokeBorder
,它依赖于.inset
正常工作,如文档中所述:TestShape
我认为创建时应用插入的方式path
可能太原始了。让我们尝试一下测试:我原本期望看到一个较小的菱形,其边缘与较大的菱形平行。
因此,我们
path
先修复该函数。这需要使用一点毕达哥拉斯和三角函数:再次尝试测试:
看起来好多了。现在让我们
strokeBorder
用原始代码再试一次:问题解决了!