将非常大的图像缩小到非常小的图像,而不会出现失真和质量损失

时间:2017-08-27 18:20:19

标签: ios swift image alamofireimage

我从后端接收的图像尺寸很大,因为我必须将相同的图像放在个人资料图片上,并在尺寸为30x30的标签栏的底栏上显示相同的图像。我试图以各种方式缩小图像,但没有任何工作。

尝试了Alamofire的方法,该方法也没有奏效(图像看起来模糊不清):

func resizeImageWithoutDistortion(image: UIImage, size : CGSize) -> UIImage{


    // 1. Scale image to size disregarding aspect ratio
    let scaledImage = image.af_imageScaled(to: size)

    // 2. Scale image to fit within specified size while maintaining aspect ratio
    let aspectScaledToFitImage = image.af_imageAspectScaled(toFit: size)

    // 3. Scale image to fill specified size while maintaining aspect ratio
    let aspectScaledToFillImage = image.af_imageAspectScaled(toFill: size)

    return scaledImage.roundImage()
}

也尝试如下,但也没有奏效:

func resizeImage(_ newWidth: CGFloat) -> UIImage {

        let ratio = size.width / size.height
        if ratio > 1 {
            UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newWidth))
            draw(in: CGRect(x: newWidth * ratio / 2 - newWidth, y: 0, width: newWidth * ratio, height: newWidth))
            let newImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()

            return newImage!.roundImage()
        } else {
            UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newWidth))
            draw(in: CGRect(x: 0, y: (newWidth / ratio - newWidth) / 2 * (-1), width: newWidth, height: newWidth / ratio))
            let newImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()

            return newImage!.roundImage()
        }
    }

在屏幕截图中,底部的图片非常扭曲。enter image description here

1 个答案:

答案 0 :(得分:0)

Ishika,你的问题不是质量损失。您的问题是您没有考虑iOS Scaling。

点数和像素相同。

如果你在W: 30 H: 30(点)中有一个UIImageView来计算你的图像(以像素为单位),以便在不影响质量的情况下清晰地显示它,你需要有一个图像像素大小 of:

30 * UIScreen.main.scale = 60像素(如果是2倍比例)

30 * UIScreen.main.scale = 90像素(如果是3倍)

这也是为什么你需要为iOS提供@ 2x和@ 3x缩放图像的原因。

因此,如果您想将UIImage调整为较小的尺寸,则需要考虑缩放比例。否则,我们会缩放您的图片以填写UIImageView,因为UIImageView大于UIImage尺寸,它们会变得模糊。

看到这个的一个好方法是,如果你设置yourImageView.contentMode = .Center,你会注意到UIImage比UIImageView本身小。

我不在Swift中编码,因此我无法为您提供直接代码(厌倦翻译),但如果您查看其他主题:

scale image to smaller size in swift3

您看到UIGraphicsBeginImageContext错过了比例输入。

  

比例

     

要应用于位图的比例因子。如果指定值   如果为0.0,则比例因子设置为设备的比例因子   主屏幕。

编辑: 在你的情况下,像这样:

newWidth = newWidth / UIScreen.main.scale

UIGraphicsBeginImageContextWithOptions(CGSize(width: newWidth, height: newWidth), true, 0)
相关问题