我正在尝试使用从 Path
创建的形状(例如六边形形状)来创建 镶嵌
Path
来表示 Shape
本身似乎很简单,但创建镶嵌似乎很棘手。
这是我用于我的
Hexagonal
的代码:
struct Hexagon: Shape {
func path(in rect: CGRect) -> Path {
var path = Path()
let center = CGPoint(x: rect.midX, y: rect.midY)
let size = min(rect.size.width, rect.size.height) / 2
let angleOffset = CGFloat.pi / 6
for i in 0..<6 {
let angle = CGFloat(i) * CGFloat.pi / 3 + angleOffset
let point = CGPoint(x: center.x + cos(angle) * size, y: center.y + sin(angle) * size)
if i == 0 {
path.move(to: point)
} else {
path.addLine(to: point)
}
}
path.closeSubpath()
return path
}
}
我想要实现的输出是这样的:
如果您允许代码了解蜂窝结构,那么布置六边形并不是太困难。这是使用六边形形状的示例,并进行了一项调整:
let size = max(rect.size.width, rect.size.height) / 2 // min -> max
struct Honeycomb: View {
private let dimension = 5
private let cellSideLength = CGFloat(25)
private var cellHeight: CGFloat {
cellSideLength * 2
}
private var cellWidth: CGFloat {
2 *
((cellSideLength * cellSideLength) - ((cellSideLength / 2) * (cellSideLength / 2))).squareRoot()
}
private var aCell: some View {
Hexagon()
.foregroundColor(.mint)
.frame(width: cellWidth, height: cellHeight)
.overlay {
Hexagon()
.stroke()
}
}
var body: some View {
VStack(spacing: cellHeight / 2) {
ForEach(0..<(dimension + 1) / 2, id: \.self) { i in
HStack(spacing: 0) {
ForEach(0..<dimension, id: \.self) { _ in
aCell
}
}
.overlay {
if i > 0 {
HStack(spacing: 0) {
ForEach(0..<dimension - 1, id: \.self) { _ in
aCell
}
}
.offset(y: -cellHeight + (cellSideLength / 2))
}
}
}
}
}
}