我以编程方式创建图片,将其转换为数据并返回并获得不同的图片。
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)
请解释发生了什么以及如何解决问题。谢谢!
最佳答案
“罪魁祸首”行:
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。
关于ios - UIImage 转换为数据并返回更改大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53682617/