I'm using AlamofireImage to download and set my UIImage:
backdrop.af_setImageWithURL(downloadURL)
The image is substantially larger than what I will be displaying and so I have an issue with aliasing. How can I resize this image properly?
Results:
You can resize the image with any size once you have a valid UIImage
:
func resizedImageWith(image: UIImage, targetSize: CGSize) -> UIImage {
let imageSize = image.size
let newWidth = targetSize.width / image.size.width
let newHeight = targetSize.height / image.size.height
var newSize: CGSize
if(newWidth > newHeight) {
newSize = CGSizeMake(imageSize.width * newHeight, imageSize.height * newHeight)
} else {
newSize = CGSizeMake(imageSize.width * newWidth, imageSize.height * newWidth)
}
let rect = CGRectMake(0, 0, newSize.width, newSize.height)
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
image.drawInRect(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
For any other queries/modifications you have, refer this NShipster
Here is @Santosh's answer in ObjC:
- (UIImage*) scaleImage:(UIImage*)image toSize:(CGSize)newSize {
CGSize imageSize = image.size;
CGFloat newWidth = newSize.width / image.size.width;
CGFloat newHeight = newSize.height / image.size.height;
CGSize newImgSize;
if(newWidth > newHeight) {
newImgSize = CGSizeMake(imageSize.width * newHeight, imageSize.height * newHeight);
} else {
newImgSize = CGSizeMake(imageSize.width * newWidth, imageSize.height * newWidth);
}
CGRect rect = CGRectMake(0, 0, newImgSize.width, newImgSize.height);
UIGraphicsBeginImageContextWithOptions(newImgSize, false, 0.0);
[image drawInRect:rect];;
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}