我有一系列自定义的Shape
和一个具有设定框架的ZStack
,有没有办法增加每个自定义Shape<的大小
可以有不同的尺寸来适应 Zstack
框架?
将绘制给定点的各种形状
的代码。
struct DrawShape: Shape {
var points: [CGPoint]
func path(in rect: CGRect) -> Path {
var path: Path = Path()
guard let startingPoint = points.first else {
return path
}
path.move(to: startingPoint)
for pointLocation in points {
path.addLine(to: pointLocation)
}
return path
}
}
最佳答案
这是我想到的:
- 像往常一样绘制路径
- 获取
boundingRect
路径的 - 确定路径所需的比例因子
-
rect
是形状的可用面积 - 如果
boundingRect
比rect
胖,使用它们的宽度 - 如果
boundingRect
比rect
更瘦,使用他们的高度
-
- 绘制一条新路径,这次使用缩放点和偏移量(如果需要)
- 如果路径的起点不是
(0, 0)
,每个新点都需要减去原点
- 如果路径的起点不是
- 返回新路径
struct DrawShape: Shape {
var points: [CGPoint]
func path(in rect: CGRect) -> Path {
/// draw the path
var path = Path()
guard let startingPoint = points.first else { return path }
path.move(to: startingPoint)
for pointLocation in points {
path.addLine(to: pointLocation)
}
/// aspect fit scale
let scale: CGFloat
if path.boundingRect.height / path.boundingRect.width < rect.height / rect.width {
scale = rect.width / path.boundingRect.width /// boundingRect is fatter
} else {
scale = rect.height / path.boundingRect.height /// boundingRect is skinnier
}
/// draw the scaled path
var scaledPath = Path()
scaledPath.move(to: convertPoint(startingPoint, offset: path.boundingRect.origin, scale: scale))
for pointLocation in points {
scaledPath.addLine(to: convertPoint(pointLocation, offset: path.boundingRect.origin, scale: scale))
}
/// return the scaled path
return scaledPath
}
/// point = original point
/// offset = in case the origin of `boundingRect` isn't (0,0), make sure to offset each point
/// scale = how much to scale the point by
func convertPoint(_ point: CGPoint, offset: CGPoint, scale: CGFloat) -> CGPoint {
return CGPoint(x: (point.x - offset.x) * scale, y: (point.y - offset.y) * scale)
}
}
struct ContentView: View {
var body: some View {
ZStack {
Color.blue
DrawShape(points: [
CGPoint(x: 0, y: 0),
CGPoint(x: 200, y: 0),
CGPoint(x: 100, y: 250),
CGPoint(x: 0, y: 0)
])
}
.frame(width: 300, height: 500)
}
}
关于ios - 给定一个自定义形状,如何增加尺寸以适应 SwiftUI 中的框架?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68093082/