如何使用 SwiftUI 将图像剪切为 2

How to cut an image into 2 using SwiftUI

我有这样一张图片

我想使用 SwiftUI 将它分成 2 个部分。给我留下 2 张我可以访问的单独图像。但是我不知道如何将原件分成顶部和底部。这两块必须排成一行才能创建原始图像。

顶部图像:

下图:

我试过使用几何图形 reader 来读取高度和宽度,并 return 使用一半高度的图像,但是这两个图像不喜欢这样。

GeometryReader { geo in
    image
       .frame(width: geo.width, height: geo.height / 2, alignment: .center)
       .clipped()
}

这里有一种方法:使用 clipped() 修饰符。



struct ContentView: View {
    
    @State private var spacing: CGFloat = CGFloat()
    @State private var imageSize: CGSize = CGSize()
    
    var body: some View {
        
        let image = Image(systemName: "star")
            .resizable()
            .scaledToFit()
            .frame(width: 200, height: 200, alignment: .center)
            .background(Color.yellow)
            .cornerRadius(10.0)
            .background(GeometryReader { proxy in Color.clear.onAppear() { imageSize = proxy.size } })
        
        
        return ZStack {
            
            VStack(spacing: spacing) {
                
                image.frame(width: imageSize.width, height: imageSize.height/2, alignment: .top).clipped()
                
                image.frame(width: imageSize.width, height: imageSize.height/2, alignment: .bottom).clipped()
            }
            
            VStack { Spacer(); Slider(value: $spacing,in: 0.0...100.0) }
            
        }
        .padding()
        .compositingGroup()
        .shadow(radius: 10.0)
        
    }
}