我有一个类似以下代码的形状:
import SwiftUI
struct ContentView: View {
var body: some View {
let myCustomInsettableShape = HexagonShape(thickness: 100.0)
ZStack {
myCustomInsettableShape
.fill(Color.blue)
myCustomInsettableShape
.strokeBorder(Color.black.opacity(0.5), style: StrokeStyle(lineWidth: 50.0, lineCap: .round, lineJoin: .miter))
}
.background(Color.red)
.padding(50)
}
}
struct HexagonShape: InsettableShape {
var thickness: CGFloat
var insetAmount: CGFloat = CGFloat.zero
func path(in rect: CGRect) -> Path {
var path: Path = Path()
let halfThickness: CGFloat = thickness/2.0
let dx: CGFloat
let dy: CGFloat
if (insetAmount > .zero) && (halfThickness > .zero) {
let diagonal = sqrt((halfThickness * halfThickness) + (halfThickness * halfThickness))
dx = insetAmount * diagonal / halfThickness
dy = insetAmount * diagonal / halfThickness
} else {
dx = .zero
dy = .zero
}
path.move(to: CGPoint(x: rect.minX + dx, y: rect.minY + halfThickness))
path.addLine(to: CGPoint(x: rect.midX, y: rect.minY + dy))
path.addLine(to: CGPoint(x: rect.maxX - dx, y: rect.minY + halfThickness))
path.addLine(to: CGPoint(x: rect.maxX - dx, y: rect.maxY - halfThickness))
path.addLine(to: CGPoint(x: rect.midX, y: rect.maxY - dy))
path.addLine(to: CGPoint(x: rect.minX + dx, y: rect.maxY - halfThickness))
path.closeSubpath()
return path
}
func inset(by amount: CGFloat) -> some InsettableShape {
var myShape: Self = self
myShape.insetAmount += amount
return myShape
}
}
形状的结果如下:
蓝色填充的形状是我想要的,并且我希望我的 strokeBorder 具有相同的形状,但我不知道如何实现 insetAmount,thickness 是一个可以改变的值,显示和说明形状的形式。
我认为几何形状是这样的:
当以此作为实施的基础时,它似乎有效: