SwiftUI:带有文本视图的混合模式使重叠区域变白,其余区域变黑

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

我正在尝试创建一个文本视图,将与另一个视图重叠的区域的颜色切换为白色,其余部分为黑色。

下面是这个问题之后的代码尝试,它使用混合模式,但它使重叠区域变成绿色,并且它基于背景视图颜色。 我希望它始终为白色,无论重叠视图颜色如何,文本视图的其余部分为黑色

struct ContentView: View {
    var body: some View {
        ZStack() {
            Color.purple.frame(width: 200, height: 40, alignment: .center)
                .offset(x: 0, y: 20)

            Text("Over")
                .foregroundColor(Color.white)
                .font(.system(size: 55, weight: .bold, design: .rounded))
                .offset(x: 10, y: 0)
                .blendMode(.difference)

        }
        .frame(width: 200, height: 100, alignment: .center)
    }
}

ios swift swiftui
2个回答
3
投票

改用 2 个文本和一个蒙版。

struct ContentView: View {
    var body: some View {
        ZStack {
            Color.purple
                .frame(width: 200, height: 40, alignment: .center)
                .offset(x: 0, y: 20)

            Text("Over")
                .foregroundColor(Color.black)
                .font(.system(size: 55, weight: .bold, design: .rounded))
                .offset(x: 10, y: 0)

            Text("Over")
                .foregroundColor(Color.white)
                .font(.system(size: 55, weight: .bold, design: .rounded))
                .offset(x: 10, y: 0)
                .mask(Rectangle().frame(height: 20).offset(x: 0, y: 10))

        }
        .frame(width: 200, height: 100, alignment: .center)
    }
}

结果:


0
投票

您在对另一个答案的评论中询问,是否有任何方法可以在不重复视图的情况下实现这一目标?当然可以在不复制文本的情况下做到这一点:

  • 混合模式
    .destinationOut
    可用于剪切文本的形式。
  • 通过应用
    .compositingView
    ,可以限制混合模式的范围。
ZStack() {
    VStack(spacing: 0) {
        Color.black
        Color.white
    }

    VStack(spacing: 0) {
        Color.white
        Color.purple
    }
    .overlay {
        Text("Over")
            .font(.system(size: 55, weight: .bold, design: .rounded))
            .blendMode(.destinationOut)
    }
    .compositingGroup()
}
.frame(width: 200, height: 100)

Screenshot

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