我正在尝试向两个形状添加蒙版,以便第二个形状遮盖第一个形状。如果我做类似的事情Circle().mask(Circle().offset(…))
,这会产生相反的效果:防止第一个圆之外的任何内容可见。
For UIView
答案在这里:iOS 在drawRect 中反转遮罩 https://stackoverflow.com/questions/14411765/ios-invert-mask-in-drawrect
然而,尝试在 SwiftUI 中实现这一点without UIView
我不明白。我尝试实现一个 InvertedShape,然后可以将其用作遮罩:
struct InvertedShape<OriginalType: Shape>: Shape {
let originalShape: OriginalType
func path(in rect: CGRect) -> Path {
let mutableOriginal = originalShape.path(in: rect).cgPath.mutableCopy()!
mutableOriginal.addPath(Path(rect).cgPath)
return Path(mutableOriginal)
.evenOddFillRule()
}
}
不幸的是,SwiftUI 路径没有addPath(Path)
(因为它们是不可变的)或evenOddFillRule()
。您可以访问路径的 CGPath 并制作可变副本,然后添加两个路径,但是,evenOddFillRule
需要设置在CGLayer
,不是CGPath
。因此,除非我能到达 CGLayer,否则我不确定如何继续。
这是 Swift 5。
这是仅通过 SwiftUI 创建倒置蒙版的可能方法的演示(在视图中打洞的示例)
func HoleShapeMask(in rect: CGRect) -> Path {
var shape = Rectangle().path(in: rect)
shape.addPath(Circle().path(in: rect))
return shape
}
struct TestInvertedMask: View {
let rect = CGRect(x: 0, y: 0, width: 300, height: 100)
var body: some View {
Rectangle()
.fill(Color.blue)
.frame(width: rect.width, height: rect.height)
.mask(HoleShapeMask(in: rect).fill(style: FillStyle(eoFill: true)))
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)