简体   繁体   中英

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.

渐变背景

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.

在此处输入图像描述

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.

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.

演示

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)
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM