In Swift programming , how do you crop an image and put it on the center afterwards?
This is what I\'ve got so far ... I\'ve successfully crop the image but I want t
Accepted answer did not work for me, so I tried wrote my own. Here is an effect of my work:
import UIKit
extension UIImage {
func cropedToRatio(ratio: CGFloat) -> UIImage? {
let newImageWidth = size.height * ratio
let cropRect = CGRect(x: ((size.width - newImageWidth) / 2.0) * scale,
y: 0.0,
width: newImageWidth * scale,
height: size.height * scale)
guard let cgImage = cgImage else {
return nil
}
guard let newCgImage = cgImage.cropping(to: cropRect) else {
return nil
}
return UIImage(cgImage: newCgImage, scale: scale, orientation: imageOrientation)
}
}
This function crop image to given ratio. It keeps image scale. Cropped image is always center of original image.