Created
February 6, 2011 06:21
-
-
Save Digitalchemy/813185 to your computer and use it in GitHub Desktop.
iOS: Crop a UIImage to the specified Rect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
Thanks!
if let croppedCGImage = (image.cgImage?.cropping(to: rect)) {
imageQR.image = UIImage(cgImage: croppedCGImage)
}
UIImage
Extension
extension UIImage {
func cropped(boundingBox: CGRect) -> UIImage? {
guard let cgImage = self.cgImage?.cropping(to: boundingBox) else {
return nil
}
return UIImage(cgImage: cgImage)
}
}
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?
@thexande Thanks sir, you make my day.
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
Swift 3 version:
I ended up using the following instead though because it was simpler for my purposes:
Thank you!