如何在SwiftUI中创建透明矩形

如何在SwiftUI中创建透明矩形,swiftui,Swiftui,我想使一个图像100%透明通过一个小矩形和50%透明从所有其他。好像开了一个小洞来看穿这个小长方形。这是我的密码 struct ImageScope: View { var body: some View { ZStack { Image("test_pic") Rectangle() .foregroundColor(Color.black.opacity(0.5))

我想使一个图像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))
        }
    }
}
为了便于理解


以下是工作方法。它用于自定义形状和奇偶填充样式

使用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)
        }
    }
}