首页 > 解决方案 > 从图像资产中获取数据

问题描述

我在资产目录中有一张图片,我需要UIImage使用 scale 参数获取这张图片 ( )。只有一种UIImage(data: scale:)方法,但我无法使用名称从资产中获取数据。我总是得到url = nil。也许问题出在目录结构上!?

我的代码:

if let url = Bundle.main.url(forResource: "countdown_photo_1", withExtension: "jpg") {
    return UIImage(data: try! Data(contentsOf: url), scale: scale)
}

我的目录结构:

在此处输入图像描述

我的 Contents.json:

{
  "images" : [
    {
      "idiom" : "universal",
      "filename" : "countdown_photo_1.jpg"
    }
  ],
  "info" : {
    "version" : 1,
    "author" : "xcode"
  }
}

标签: swiftuiimageassets

解决方案


试试这个代码可能对你有用

guard let img = UIImage(named: "countdown_photo_1.jpg") else { return }
let data = img.jpegData(compressionQuality: 1)

推荐阅读