【发布时间】:2020-02-19 23:13:41
【问题描述】:
TL;DR:我使用Path 来指定Image 的命中区域。但我不知道如何调整 Path 坐标以匹配 SwiftUI 决定的布局......或者我什至需要这样做。
运行时
我的(测试)应用看起来像这样,Image 边框(不是帧)为清楚起见着色:
我想要是让Image 处理不透明橙色的水龙头。在不透明的橙色之外点击——即使在橙色图像的范围内——应该“穿过”到绿色图像或灰色背景。但不是。 (紫色轮廓显示路径的位置,根据自身情况;请参见下面的代码)。
详情
这是图像的内在(以像素为单位)布局:
不透明部分周围的路径很容易被视为
[(200, 200), (600, 200), (600, 600), (200, 600)]
这些坐标和Image 坐标有什么关系?
代码
extension CGPoint {
typealias Tuple = (x:CGFloat, y:CGFloat)
init(tuple t: Tuple) {
self.init(x: t.x, y: t.y)
}
}
struct ContentView: View {
var points = [(200, 200), (600, 200), (600, 600), (200, 600)]
.map(CGPoint.init(tuple:))
// .map { p in p.shifted(dx:-64, dy:-10)} // Didn't seem to help.
var path : Path {
var result = Path()
result.move(to: points.first!)
result.addLines(points)
result.closeSubpath()
return result
}
var body: some View {
ZStack{
Image("gray") // Just so we record all touches.
.resizable()
.frame(maxWidth : .infinity,maxHeight: .infinity)
.onTapGesture {
print("background")
}
Image("square_green")
.resizable()
.scaledToFit()
.border(Color.green, width: 4)
.offset(x: 64, y:10) // So the two Images don't overlap completely.
.onTapGesture {
print("green")
}
Image("square_orange")
.resizable()
.scaledToFit()
.contentShape(path) // Magic should happen here.
.border(Color.orange, width: 4)
.offset(x: -64, y:-10)
// .contentShape(path) // Didn't work here either.
.onTapGesture {
print("orange")
}
path.stroke(Color.purple) // Origin at absolute (200,200) as expected.
}
}
}
【问题讨论】:
标签: layout swiftui mask hittest