iosswiftuisubviewclippingzstack

How to clip subviews using ZStack with SwiftUI?


I need to clip the view behind a Text by using its Rectangle. When I add a Text over this 1-pixel height rectangle, I need it to "clip" the subview below, so the text can be readable.

gradient background

Of course, if I use a solid background color, it's easy to do, as I just set it and it will clip the subview.

enter image description here

Here is a POC to test it:

struct test: View {
  let gradient = Gradient(colors: [Color.blue, Color.purple])
  
  var body: some View {
    ZStack {
      Rectangle()
        .fill(LinearGradient(gradient: gradient, startPoint: .leading, endPoint: .trailing))
        .frame(width: 200, height: 200)
        
      ZStack {
        Rectangle()
          .fill(Color.white)
          .frame(width: 100, height: 1, alignment: .center)
        Text("XXXX")
          .background(Color.green)
      }
    }
  }
}

Any ideas? I don't think I can handle it using a mask.


Solution

  • Sometimes a solution might be not-to-do instead of to-do-but.

    Here is a possible implementation of above principle to solve your issue.

    demo

    var body: some View {
        ZStack {
            Rectangle()
                .fill(LinearGradient(gradient: gradient, startPoint: .leading, endPoint: .trailing))
                .frame(width: 200, height: 200)
    
            HStack(spacing: 0) {
                Rectangle()
                    .fill(Color.white)
                    .frame(width: 30, height: 1, alignment: .center)
                Text("XXXX")
                Rectangle()
                    .fill(Color.white)
                    .frame(width: 30, height: 1, alignment: .center)
            }
        }