In my application, I have set one image in UIImageView and the size of UIImageView is 320 x 170. but the size of original image is 320 x 460. so how to crop this image and d
Maybe someone is interested in the Swift version of the answer @tirth gave. It is written as a UIImage
extension. As an example I added another method to crop the image to be a center square version.
// MARK: - UIImage extension providing function to crop an image to a rect
extension UIImage {
/**
Return a cropped image from an existing image
- parameter toRect: a rectangular region for a new image
- returns: new image instance
*/
func croppedImage(toRect: CGRect) -> UIImage {
// create new CGImage reference
let imageRef = CGImageCreateWithImageInRect(self.CGImage, toRect)
// create and return new UIImage
return UIImage(CGImage: imageRef!)
}
/**
Crop center rect from possibly rectangular image
- returns: return self in case image is already square, new center rect otherwise
*/
func cropCenterRect() -> UIImage {
// image might already be square
if self.size.height == self.size.width {
return self
}
// portrait
if self.size.height > self.size.width {
// calculate offset at top and bottom
let offset = (self.size.height - self.size.width) / 2.0
// return cropped image
return self.croppedImage(CGRect(x: 0.0, y: offset, width: self.size.width, height: self.size.width))
} else {
// landscape
// calculate offset left and right
let offset = (self.size.width - self.size.height) / 2.0
// return cropped image
return self.croppedImage(CGRect(x: offset, y: 0.0, width: self.size.height, height: self.size.height))
}
}
}