簡體   English   中英

在 SwiftUI 中,如何使用另一個視圖剪輯視圖的一部分?

[英]In SwiftUI how can I clip a part of a view with another view?

我試圖在 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 中剪輯我的大圓圈的底部嗎?

這是一個使用倒置掩碼的可能方法的演示(它被簡化了,但想法應該很清楚 - 刪除硬編碼和“咬”位置計算在你身上)。

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

    }
}

備份

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM