Skip to content

Instantly share code, notes, and snippets.

@Digitalchemy
Created February 6, 2011 06:21
Show Gist options
  • Save Digitalchemy/813185 to your computer and use it in GitHub Desktop.
Save Digitalchemy/813185 to your computer and use it in GitHub Desktop.
iOS: Crop a UIImage to the specified Rect
// Crop a UIImage to the specified cropRect
public UIImage CropImage(UIImage image, RectangleF cropRect)
{
UIGraphics.BeginImageContextWithOptions(cropRect.Size, false, 0);
var context = UIGraphics.GetCurrentContext();
context.TranslateCTM(0.0f, image.Size.Height);
context.ScaleCTM(1.0f, -1.0f);
context.DrawImage(new RectangleF(0, 0, image.Size.Width, image.Size.Height), image.CGImage);
context.ClipToRect(cropRect);
var croppedImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return croppedImage;
}
@Wavewash
Copy link

Wavewash commented Jan 6, 2018

Swift 3 version:

    private func CropImage( image:UIImage , cropRect:CGRect) -> UIImage
    {
        UIGraphicsBeginImageContextWithOptions(cropRect.size, false, 0);
        let context = UIGraphicsGetCurrentContext();
        
        context?.translateBy(x: 0.0, y: image.size.height);
        context?.scaleBy(x: 1.0, y: -1.0);
        context?.draw(image.cgImage!, in: CGRect(x:0, y:0, width:image.size.width, height:image.size.height), byTiling: false);
        context?.clip(to: [cropRect]);
    
        let croppedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return croppedImage!;
    }

I ended up using the following instead though because it was simpler for my purposes:

    //image is of type UIImage
    //boundingBox is of type CGRect
    let croppedCGImage:CGImage = (image!.cgImage?.cropping(to: boundingBox))!
    let croppedImage = UIImage(cgImage: croppedCGImage)

Thank you!

@superarts
Copy link

Thanks!

	if let croppedCGImage = (image.cgImage?.cropping(to: rect)) {
		imageQR.image = UIImage(cgImage: croppedCGImage)
	}

@thexande
Copy link

UIImage Extension

extension UIImage {
    func cropped(boundingBox: CGRect) -> UIImage? {
        guard let cgImage = self.cgImage?.cropping(to: boundingBox) else {
            return nil
        }

        return UIImage(cgImage: cgImage)
    }
}

@vineeshtp
Copy link

Working fine. But, After edit image is rotating. How do I change this.

@bysnrk
Copy link

bysnrk commented Jul 7, 2018

Have the same problem with rotation. Cropped image rotated 90 degrees CCW. Any solution?

@cmdr-surender-singh
Copy link

@thexande Thanks sir, you make my day.

@lukelucas247
Copy link

lukelucas247 commented Feb 19, 2019

Working fine. But, After edit image is rotating. How do I change this.

Have the same problem with rotation. Cropped image rotated 90 degrees CCW. Any solution?

https://developer.apple.com/documentation/uikit/uiimage/orientation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment