I am working on the custom camera application. Things are working good.
But I got into the problem while cropping the image from bottom. i.e. cropped image is having exact same width as the original image but height will be 1/3 of the original image and it must start from the bottom.
Swift 3 solution:
func cropBottomImage(image: UIImage) -> UIImage {
let height = CGFloat(image.size.height / 3)
let rect = CGRect(x: 0, y: image.size.height - height, width: image.size.width, height: height)
return cropImage(image: image, toRect: rect)
}
Helper method for cropping with a rect:
func cropImage(image:UIImage, toRect rect:CGRect) -> UIImage{
let imageRef:CGImage = image.cgImage!.cropping(to: rect)!
let croppedImage:UIImage = UIImage(cgImage:imageRef)
return croppedImage
}
this is almost Alexburtnik's answer
but just to mention that UIImage.size is the logical size (in "points")
however, CGImage.cropping() used the actual dimension (in "pixels")
therefore, if you use a image with @2x or @3x modifiers, you will find the cropping is actually half or one third of the expectation.
so when you crop, you may consider multiplying the rect by the "scale" property of the image first, like the following:
func cropImage(image:UIImage, toRect rect:CGRect) -> UIImage? {
var rect = rect
rect.size.width = rect.width * image.scale
rect.size.height = rect.height * image.scale
guard let imageRef = image.cgImage?.cropping(to: rect) else {
return nil
}
let croppedImage = UIImage(cgImage:imageRef)
return croppedImage
}
As an extension to UIImage:
import UIKit
extension UIImage {
func crop(to rect: CGRect) -> UIImage? {
// Modify the rect based on the scale of the image
var rect = rect
rect.size.width = rect.size.width * self.scale
rect.size.height = rect.size.height * self.scale
// Crop the image
guard let imageRef = self.cgImage?.cropping(to: rect) else {
return nil
}
return UIImage(cgImage: imageRef)
}
}
Usage:
let myImage = UIImage(named:"myImage.png")
let croppedRect = CGRect(x: 0, y: 0, width: newWidth, height: newHeight)
let croppedImage = myImage.crop(to: croppedRect)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With