iOS Swift: How to properly scale down an image?

2020-03-07 04:46发布

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:

enter image description here

2条回答
劫难
2楼-- · 2020-03-07 05:30

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;
}
查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-03-07 05:36

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

查看更多
登录 后发表回答