How make a ImageCropper like Instagram with Swift 3

Aatish Rajkarnikar
2 min readFeb 14, 2017

--

I am very overwhelmed with the responses from my last blog about How to make a Image Cropper with Swift 3. I am very happy that it helped lots of developers.

Many people have been asking me about how they can make a Image Cropper like in Instagram. so, here i am, writing a short and sweet tutorial on making your own Image Cropper like in Instagram.

Lets get started…

Create a ScrollView with any frame you like, for this tutorial i have ScrollView with aspect ratio 4:3

Add ImageView in ScrollView and give Leading, Trailing, Top , Bottom constraints with ScrollView. Give Height and Width constraint to the ImageView.

Make outlet of ScrollView, ImageView, ImageView’s height constraint and ImageView’s width constraint.

@IBOutlet var scrollView: UIScrollView!@IBOutlet var imageView: UIImageView!@IBOutlet var imageViewWidth: NSLayoutConstraint!@IBOutlet var imageViewHeight: NSLayoutConstraint!

Confirm the UIScrollViewDelegate protocol and implement one of its function which returns imageView to have pinch to zoom feature.

func viewForZooming(in scrollView: UIScrollView) -> UIView? {return imageView}

Create a function that set image to ImageView with additional setup to ScrollView. Make the size of ImageView equal to image that needs to be cropped. then, we need to find out minimum zoom scale for ScrollView so, get the max value between scale height and scale width and set it to ScrollView’s minimum zoom scale and current zoom scale.

func setImageToCrop(image:UIImage){
imageView.image = image
imageViewWidth.constant = image.size.width imageViewHeight.constant = image.size.height let scaleHeight = scrollView.frame.size.width/image.size.width let scaleWidth = scrollView.frame.size.height/image.size.height let maxScale = max(scaleWidth, scaleHeight) scrollView.minimumZoomScale = maxScale scrollView.zoomScale = maxScale}

and finally to perform the cropping, we need a frame of cropping area with respect to original Image. so, to calculate the cropping area, get the scale factor from the ScrollView and scale the current cropping area by multiplying with scale factor.

func crop() {    let scale:CGFloat = 1/scrollView.zoomScale    let x:CGFloat = scrollView.contentOffset.x * scale    let y:CGFloat = scrollView.contentOffset.y * scale    let width:CGFloat = scrollView.frame.size.width * scale    let height:CGFloat = scrollView.frame.size.height * scale    let croppedCGImage = imageView.image?.cgImage?.cropping(to: CGRect(x: x, y: y, width: width, height: height))    let croppedImage = UIImage(cgImage: croppedCGImage!)    setImageToCrop(image: croppedImage)}

now, you can use croppedImage as you like.

Hope you liked it. if there is any feedback, i will really appreciate it. ☺️ Thank you!! 🙏

Example Project: https://github.com/aatish-rajkarnikar/ImageCropper2

--

--