我想通过一个小矩形使图像 100% 透明,并使所有其他图像 50% 透明。好像打了一个小孔来透视这个小矩形。这是我的代码...
struct ImageScope: View {
var body: some View {
ZStack {
Image("test_pic")
Rectangle()
.foregroundColor(Color.black.opacity(0.5))
Rectangle()
.frame(width: 200, height: 150)
.foregroundColor(Color.orange.opacity(0.0))
.overlay(RoundedRectangle(cornerRadius: 3).stroke(Color.white, lineWidth: 3))
}
}
}
Run Code Online (Sandbox Code Playgroud)
为了更容易理解...
这是工作方法。它使用自定义形状和奇偶填充样式。
使用 Xcode 11.4 / iOS 13.4 测试
下面的演示具有更高的透明度对比度以获得更好的可见性。
struct Window: Shape {
let size: CGSize
func path(in rect: CGRect) -> Path {
var path = Rectangle().path(in: rect)
let origin = CGPoint(x: rect.midX - size.width / 2, y: rect.midY - size.height / 2)
path.addRect(CGRect(origin: origin, size: size))
return path
}
}
struct ImageScope: View {
var body: some View {
ZStack {
Image("test_pic")
Rectangle()
.foregroundColor(Color.black.opacity(0.5))
.mask(Window(size: CGSize(width: 200, height: 150)).fill(style: FillStyle(eoFill: true)))
RoundedRectangle(cornerRadius: 3).stroke(Color.white, lineWidth: 3)
.frame(width: 200, height: 150)
}
}
}
Run Code Online (Sandbox Code Playgroud)
使用时blendMode(.destinationOut)您不必绘制自定义形状,并且只需一行代码。有时添加.compositingGroup()修饰符是必要的。
ZStack {
Color.black.opacity(0.5)
Rectangle()
.frame(width: 200, height: 200)
.blendMode(.destinationOut) // << here
}
.compositingGroup()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2065 次 |
| 最近记录: |