iOS Swift:如何正确缩小图像?

时间:2016-06-27 20:01:43

标签: ios swift uiimageview aliasing alamofireimage

我正在使用AlamofireImage下载并设置我的UIImage:

backdrop.af_setImageWithURL(downloadURL)

图像比我要显示的图像大得多,所以我遇到了锯齿问题。如何正确调整此图像的大小?

结果:

enter image description here

2 个答案:

答案 0 :(得分:5)

一旦您拥有有效的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
}

如果您有任何其他疑问/修改,请参阅此NShipster

答案 1 :(得分:0)

这是@Santosh在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;
}