Using Swift 3
Image cropping can be done using CGImages from CoreGraphics.
Get the CGImage version of a UIImage like this:
// cgImage is an attribute of UIImage
let cgImage = image.cgImage
CGImage objects have a method cropping(to: CGRect) that does the cropping:
let croppedCGImage: CGImage = cgImage.cropping(to: toRect)
Finally, convert back from CGImage to UIImage:
let uiImage = UIImage(cgImage: croppedCGImage)
Example function:
func cropImage(image: UIImage, toRect: CGRect) -> UIImage? {
// Cropping is available trhough CGGraphics
let cgImage :CGImage! = image.cgImage
let croppedCGImage: CGImage! = cgImage.cropping(to: toRect)
return UIImage(cgImage: croppedCGImage)
}
The CGRect attribute of cropping defines the 'crop rectangle' inside the image that will be cropped.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…