如何在 SwiftUI 中遮盖/裁剪图像的底部?

cyr*_*ril 4 swiftui

目前,在 SwiftUI 中屏蔽图像似乎非常简单,可以使用以下方法来实现:

.clipShape(RoundedRectangle(cornerRadius:20,
                                        style: .continuous))
Run Code Online (Sandbox Code Playgroud)

甚至.mask().center有没有办法通过指定、 、 .etc来控制图像的哪一部分被屏蔽.bottom?到目前为止,我一直在尝试偏移,但我想知道是否有更简单的方法。

kon*_*iki 5

.clipShape()需要一个形状,因此如果您要经常修剪底部,则可以创建一个临时形状。像这样的东西:

import SwiftUI

struct ContentView: View {
    var body: some View {
        Image("mypic")
            .aspectRatio(contentMode: .fit)
            .clipShape(BottomClipper(bottom: 100))
    }
}

struct BottomClipper: Shape {
    let bottom: CGFloat

    func path(in rect: CGRect) -> Path {
        Rectangle().path(in: CGRect(x: 0, y: rect.size.height - bottom, width: rect.size.width, height: bottom))
    }
}
Run Code Online (Sandbox Code Playgroud)