非矩形图像裁剪 SwiftUI?

时间:2021-03-25 03:36:21

标签: ios swift image swiftui crop

我想允许用户通过在原始图像上绘制闭合形状来裁剪图像。有点像 Snapchat 贴纸。我从 2012 年开始查看此 post,并且很好奇是否有更新的方法可以使用 SwiftUI 来执行此操作。

为了澄清,我想在显示的图像上进行用户输入(绘图)并使用该形状的遮罩裁剪实际图像(而不是视图)。

1 个答案:

答案 0 :(得分:2)

实际上您的问题需要更具体。

但是您可以在 swift ui 中通过以下代码调整图像大小。

Image("Your Image name here!")
    .resizable()
    .frame(width: 300, height: 300)
    

如果你想在图像的任何位置裁剪,你可以试试这个

import SwiftUI

struct ContentView: View {
    var body: some View {
        
        CropImage(imageName: "Your Image name here!")
        
    }
}

// struct Shape
struct CropFrame: Shape {
    let isActive: Bool
    func path(in rect: CGRect) -> Path {
        guard isActive else { return Path(rect) } // full rect for non active
        
        let size = CGSize(width: UIScreen.main.bounds.size.width*0.7, height: UIScreen.main.bounds.size.height/5)
        let origin = CGPoint(x: rect.midX - size.width/2, y: rect.midY - size.height/2)
        return Path(CGRect(origin: origin, size: size).integral)
    }
}

// struct image crop
struct CropImage: View {
    
    let imageName: String
    
    @State private var currentPosition: CGSize = .zero
    @State private var newPosition: CGSize = .zero
    @State private var clipped = false
    
    var body: some View {
        
        VStack {
            
            ZStack {
                
                Image(imageName)
                    .resizable()
                    .scaledToFit()
                    .offset(x: currentPosition.width, y: currentPosition.height)
                
                Rectangle()
                    .fill(Color.black.opacity(0.3))
                    .frame(width: UIScreen.main.bounds.size.width*0.7 , height: UIScreen.main.bounds.size.height/5)
                    .overlay(Rectangle().stroke(Color.white, lineWidth: 3))
            }
            .clipShape(
                CropFrame(isActive: clipped)
            )
            .gesture(DragGesture()
                        .onChanged { value in
                            currentPosition = CGSize(width: value.translation.width + newPosition.width, height: value.translation.height + newPosition.height)
                        }
                        .onEnded { value in
                            currentPosition = CGSize(width: value.translation.width + newPosition.width, height: value.translation.height + newPosition.height)
                            
                            newPosition = currentPosition
                        })
            
            
            Button (action : { clipped.toggle() }) {
                
                Text("Crop Image")
                    .padding(.all, 10)
                    .background(Color.blue)
                    .foregroundColor(.white)
                    .shadow(color: .gray, radius: 1)
                    .padding(.top, 50)
                
            }
        }
    }
}

这是带有图像裁剪的视图的完整代码。

否则您可以使用 GitHub 中的库,请参阅 GitHub demo here