UIImage 转换为数据并返回更改大小?

UIImage convert to data and back changes size?

我以编程方式创建图片,将其转换为数据并返回并得到不同的图片。

    let image1: UIImage = {
        let size = CGSize(width: 50, height: 50)
        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        UIColor.black.setFill()
        UIRectFill(rect)
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }()
    let data = UIImagePNGRepresentation(image1)!
    let image2 = UIImage(data: data)!
    print(image1.size) // (50.0, 50.0)
    print(image2.size) // (100.0, 100.0)

请解释发生了什么以及如何解决问题。谢谢!

"culprit"行:

UIGraphicsBeginImageContextWithOptions(size, false, 0)

查看 UIGraphicsBeginImageContextWithOptions() 的文档,了解最后一个参数 (scale)

scale
The scale factor to apply to the bitmap. If you specify a value of 0.0, the scale factor is set to the scale factor of the device’s main screen.

如果您的设备是 Retina (*2),则比例因子将为 2。