在 SwiftUI 中将不透明度应用于 ZStack

f3d*_*m76 6 opacity ios swiftui

这是我的两个重叠矩形的代码,并对它们应用了不透明度。

var body: some View {
    let r = Rectangle()
        .foregroundColor(.blue)
        .frame(width: 80, height: 40)
        .position(x: 60, y: 110)

    let r2 = Rectangle()
        .foregroundColor(.green)
        .frame(width: 80, height: 40)
        .position(x: 70, y: 120)

    return ZStack {
        r
        r2
    }.opacity(0.5)
}
Run Code Online (Sandbox Code Playgroud)

它们看起来像这样:

它们需要看起来像这样(红色矩形只是为了更好地看到不透明度):

所以我想说的是蓝色矩形在绿色矩形下面不应该是可见的。因为不透明度应该作为一个组应用于它们,而不是一个一个地单独应用于它们中的每一个。我怎样才能做到这一点?

Asp*_*eri 7

在不透明度修改器之前使用合成组,例如

演示

return ZStack {
    r
    r2
}
.compositingGroup()    // << here !!
.opacity(0.5)
Run Code Online (Sandbox Code Playgroud)