SwiftUI 中 .compositingGroup() 的目的是什么?

use*_*557 6 swiftui

我无法弄清楚 compositingGroup() 是什么。起初,我认为它类似于Merging layersPhotoshop 中的东西。但事实并非如此。因为即使我使用 .compositingGroup(),.shadow() 也会分别对叠加视图和背景视图产生影响。

到目前为止,我在使用 .compositingGroup() 时发现了两个不同之处

  • 文字没有阴影。
  • 叠加视图的阴影大小比上面的略小。

compositingGroup 的目的是什么?

struct ContentView: View {
    var body: some View {
        VStack(spacing: 50) {
            Text("Without\ncompositing")
                .font(.largeTitle)
                .bold()
                .padding()
                .foregroundColor(Color.white)
                .background(RoundedRectangle(cornerRadius: 30).fill(Color.red))
                .padding()
                .padding()
                .overlay(RoundedRectangle(cornerRadius: 30).stroke(lineWidth: 10))
                .shadow(color: .blue, radius: 5)

            Text("With\ncompositing")
                .font(.largeTitle)
                .bold()
                .padding()
                .foregroundColor(Color.white)
                .background(RoundedRectangle(cornerRadius: 30).fill(Color.red))
                .padding()
                .padding()
                .overlay(RoundedRectangle(cornerRadius: 30).stroke(lineWidth: 10))
                .compositingGroup() // <--- I added .compositingGroup() here.
                .shadow(color: .blue, radius: 5)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

ram*_*nok 25

此修饰符使以下修饰符应用于整个视图,而不是单独应用于每个特定的子视图

下面是一个例子来更好地说明这一点:

struct ContentView: View {
    let circles: some View = ZStack {
        Circle()
            .frame(width: 100, height: 100)
            .foregroundColor(.red)
            .offset(y: -25)

        Circle()
            .frame(width: 100, height: 100)
            .foregroundColor(.blue)
            .offset(x: -25, y: 25)

        Circle()
            .frame(width: 100, height: 100)
            .foregroundColor(.green)
            .offset(x: 25, y: 25)
    }

    var body: some View {
        VStack(spacing: 100) {
            circles

            circles
                .opacity(0.5)

            circles
                .compositingGroup()
                .opacity(0.5)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

结果

因此,在您的情况下,阴影将应用于整个视图,而不是单独应用于并Text覆盖RoundedRectangle

  • 非常好的例子! (2认同)