如何在 SwiftUI 中创建透明矩形

Asi*_*Das 4 swiftui

我想通过一个小矩形使图像 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)

为了更容易理解...

在此处输入图片说明

Asp*_*eri 7

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

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


eja*_*a08 6

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

  • 我尝试了这个和一些变体,但无法让它工作。我认为这个答案需要更多的解释和/或代码(使用图像)。 (2认同)
  • @Marcy 请尝试在“ZStack”上添加“.compositingGroup()”修饰符。 (2认同)