user9914227
user9914227

Reputation:

Swift: CropView for UIImageView

I'm looking for a tutorial to tell me how to create a frame to crop the photo, as the picture below

Sample

thanks

Upvotes: 2

Views: 1890

Answers (1)

AamirR
AamirR

Reputation: 12198

As a first step please look into implementing a UIView that resizes using the corners/handles. This post should help

Once we have a resizable UIView, then using UIView.frame's origin and size to crop the image, like so:

extension UIImage {

    func crop(size: CGSize, offset: CGPoint, scale: CGFloat = 1.0) -> UIImage? {
        let rect = CGRect(x: offset.x * scale, y: offset.y * scale, width: size.width * scale, height: size.height * scale)
        if let cropped = self.cgImage?.cropping(to: rect) {
            return UIImage(cgImage: cropped)
        }
        return nil
    }

}

let croppedImage = image.crop(size: resizableView.frame.size, offset: resizableView.frame.origin)

Upvotes: 1

Related Questions