swiftui BlendMode 与草图组合差异模式不匹配

问题描述 投票:0回答:2

我想显示与矩形结合的文本,如下图所示。我已经通过组合差异形状模式将其绘制在草图中。

我在Xcode中使用SwiftUI进行编码,代码如下:

struct DiffView: View {
    var body: some View {
        ZStack() {
            Rectangle()
                .fill(Color.blue)
                .frame(width: 50, height: 50, alignment: .center)
            Text("DIFF")
                .foregroundColor(Color.blue)
                .font(.system(size: 30, weight: .bold, design: .rounded))
                .blendMode(.difference)
                .offset(x: 20, y: 0)
                
        }
        .frame(width: 100, height: 100, alignment: .center)
        .background(Color.white)
    }
}

但是结果并没有像Sketch中预期的那样,左边重叠的部分变成了黑色(预计是白色),右边的字母变成了黄色(预计是蓝色)。

我应该如何正确使用 swiftui BlendMode?

enter code here

ios layout swiftui sketchapp
2个回答
3
投票

它考虑了背景,因此蓝色与白色的差异会产生橙色。首先,我们使用

compositingGroup

从混合中删除背景
struct DiffView: View {
    var body: some View {
        ZStack() {
                Color.blue
                .frame(width: 50, height: 50, alignment: .center)
            Text("DIFF")
                .foregroundColor(Color.blue)
                .font(.system(size: 30, weight: .bold, design: .rounded))
                .offset(x: 20, y: 0)
                .blendMode(.difference)
        }
        .compositingGroup()
        .frame(width: 100, height: 100, alignment: .center)
    }
}

这给出了

这是因为纯粹的差异在背景中没有任何东西,因此给出了

black
颜色。所以你的效果可以通过以下方式达到

struct DiffView: View {
    var body: some View {
        ZStack() {
                Color.orange
                .frame(width: 50, height: 50, alignment: .center)
            Text("DIFF")
                .foregroundColor(Color.orange)
                .font(.system(size: 30, weight: .bold, design: .rounded))
                .offset(x: 20, y: 0)
                .blendMode(.difference)
        }
        .compositingGroup()
        .colorInvert()
        .frame(width: 100, height: 100, alignment: .center)
    }
}


0
投票

这是一个迟来的答案,展示了使用混合模式实现此目的的另一种方法

.destinationOut

  • 这种混合模式允许将文本的形式从其下面的内容中“剪切”出来。
  • 修改器
    .compositingView
    然后限制混合模式的范围,允许
    ZStack
    中的其他内容提供背景。
ZStack {
    HStack(spacing: 0) {
        Color.white
        Color.blue
    }

    HStack(spacing: 0) {
        Color.blue
        Color.white
    }
    .overlay(alignment: .leading) {
        Text("DIFF")
            .font(.system(size: 30, weight: .bold, design: .rounded))
            .padding(.leading, 10)
            .blendMode(.destinationOut)
    }
    .compositingGroup()
}
.frame(width: 100, height: 50)

Screenshot

© www.soinside.com 2019 - 2024. All rights reserved.