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

问题描述

我有一张这样的图片

enter image description here

我想使用 SwiftUI 将它分成 2 部分横跨中心。给我留下了 2 张我可以访问的独立图像。但是我不知道如何将原件分成顶部和底部。两个部分必须对齐才能创建原始图像。

上图:

enter image description here

下图:

enter image description here

我尝试使用几何阅读器读取高度和宽度并返回高度一半的图像,但是这两个图像不喜欢这样。

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

解决方法

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


enter image description here


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,alignment: .bottom).clipped()
            }
            
            VStack { Spacer(); Slider(value: $spacing,in: 0.0...100.0) }
            
        }
        .padding()
        .compositingGroup()
        .shadow(radius: 10.0)
        
    }
}