【问题标题】:In SwiftUI how can I clip a part of a view with another view?在 SwiftUI 中,如何使用另一个视图剪辑视图的一部分?
【发布时间】:2022-08-23 21:50:05
【问题描述】:

我试图在 SwiftUI 中重叠两个圆圈并在它们之间留出一个边距。我目前正在使用这种方法:

ZStack {
    Circle()
        .frame(width: 60, height: 60)
        .foregroundColor(Color.blue)
        .shadow(color: .black.opacity(0.5), radius: 4, x: 2, y: 2)
    ZStack {
        Circle()
            .frame(width: 26, height: 26)
            .foregroundColor(Color(.systemGray5))
        Circle()
            .frame(width: 22, height: 22)
            .foregroundColor(.blue)
    }
    .offset(x: 26, y: 17)
}

问题是,由于大圆圈上的阴影,我永远无法完美匹配小圆圈边框圆上的背景(即 systemGray5。所以虽然看起来不错,但我只想要边距出现在圆圈之间。不是一直围绕较小的圆圈。

在插画家或其他方式中,我会用我的 26 号圆圈剪辑大图像,它看起来就像被咬了一口。那么我就可以完美的达到这个效果了。

无论如何要在 SwiftUI 中剪辑我的大圆圈的底部吗?

    标签: ios xcode swiftui


    【解决方案1】:

    这是一个使用倒置掩码的可能方法的演示(它被简化了,但想法应该很清楚 - 删除硬编码和“咬”位置计算在你身上)。

    使用 Xcode 13.2 / iOS 15.2 测试

    struct DemoView: View {
        struct BiteCircle: Shape {
            func path(in rect: CGRect) -> Path {
                let offset = rect.maxX - 26
                let crect = CGRect(origin: .zero, size: CGSize(width: 26, height: 26)).offsetBy(dx: offset, dy: offset)
    
                var path = Rectangle().path(in: rect)
                path.addPath(Circle().path(in: crect))
                return path
            }
        }
        var body: some View {
            ZStack {
                Circle()
                    .frame(width: 60, height: 60)
                    .foregroundColor(Color.blue)
                    .mask(BiteCircle().fill(style: .init(eoFill: true)))     // << here !!
                    .shadow(color: .black.opacity(0.5), radius: 4, x: 2, y: 2)
    
                Circle()
                    .frame(width: 22, height: 22)
                    .foregroundColor(.blue)
                    .offset(x: 18, y: 18)
            }
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-06-21
      • 1970-01-01
      • 2021-10-15
      • 2021-06-28
      • 2020-12-06
      • 1970-01-01
      • 1970-01-01
      • 2021-03-26
      • 2021-07-29
      相关资源
      最近更新 更多