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

标签 ios swift uiimage

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

    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/

相关文章:

ios - 如何使用 GPUImage 实现 GPUImageMaskFilter

ios - 如何获取 uitableview 部分的索引路径?

ios - UINavigationBar下的自定义UISearchBar错误的色调

ios - 在 32 位 iPhone 上处理 64 位整数

ios - 在 View Controller 呈现动画期间响应触摸事件

ios - 在 UIButton 中,setImage 和 setBackgroudnImage content id 不同,它旋转了 90 度

ios - Alamofire 传递具有公共(public)键和多个值的参数?

ios - 显示不同选项的 MPVolume View

ios - 使用视觉格式约束时, subview 未显示在 ScrollView 中

swift 4 : nil loading local UIImage