So here\'s where I\'ve made it so far. I am using a UIImage captured from the camera and can crop the center square when in landscape. For some reason this doesn\'t transl
Solution based on Swift 2 extension. Improvised from @Geoffrey and @Nirav Dangi. Note that we set newCropWidth and newCropHeight to image's width or height when they are lesser than the given width or height.
extension UIImage {
func imageByCroppingImage(size: CGSize) -> UIImage {
let newCropWidth, newCropHeight : CGFloat;
if(self.size.width < self.size.height) {
if (self.size.width < size.width) {
newCropWidth = self.size.width;
}
else {
newCropWidth = size.width;
}
newCropHeight = (newCropWidth * size.height)/size.width;
} else {
if (self.size.height < size.height) {
newCropHeight = self.size.height;
}
else {
newCropHeight = size.height;
}
newCropWidth = (newCropHeight * size.width)/size.height;
}
let x = self.size.width / 2 - newCropWidth / 2;
let y = self.size.height / 2 - newCropHeight / 2;
let cropRect = CGRectMake(x, y, newCropWidth, newCropHeight);
let imageRef = CGImageCreateWithImageInRect(self.CGImage, cropRect);
let croppedImage : UIImage = UIImage(CGImage: imageRef!, scale: 0, orientation: self.imageOrientation);
return croppedImage;
}
}