70

次のように表示されます。

[[NSBundle mainBundle] pathForResource:@"name" ofType:@"png"];

Images.xcassets アセット カタログ内にあるアセットについては何も返しません。私も試しました:

[[NSBundle mainBundle] pathForResource:@"name" ofType:@"png" inDirectory:@"Images"];

[[NSBundle mainBundle] pathForResource:@"name" ofType:@"png" inDirectory:@"Images.xcassets"];

しかし、どちらも機能しませんでした。

カタログ内のアセットへのパスの取得に成功した人はいますか?

4

6 に答える 6

12

ローカル リソースで作成するためにいくつかのベクター アセットにアクセスしたかったUNNotificationAttachmentので、このヘルパー クラスを思いつきました。基本的には、アセットから画像を取得し、そのデータをディスクに保存して、ファイル URL を返すだけです。それが誰かを助けることを願っています。

import UIKit

class AssetExtractor {

    static func createLocalUrl(forImageNamed name: String) -> URL? {

        let fileManager = FileManager.default
        let cacheDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0]
        let url = cacheDirectory.appendingPathComponent("\(name).png")

        guard fileManager.fileExists(atPath: url.path) else {
            guard
                let image = UIImage(named: name),
                let data = UIImagePNGRepresentation(image)
            else { return nil }

            fileManager.createFile(atPath: url.path, contents: data, attributes: nil)
            return url
        }

        return url
    }

}
于 2016-09-28T13:28:49.837 に答える
11
[UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.png", [[NSBundle mainBundle] resourcePath], imgName]];

imgName: 画像セットの名前。画像セット内の画像の本当の名前は気にしません。

于 2014-09-24T03:27:05.963 に答える
2

「アセット カタログのコンパイル」手順で決定したイメージ名を使用してみてください。これは、ビルド出力で見つかります。必ずトランスクリプトを展開してください。次のように表示されます。

/* com.apple.actool.compilation-results */
/path/to/Debug-iphonesimulator/Your.app/LaunchImage-800-Portrait-736h@3x.png
/path/to/Debug-iphonesimulator/Your.app/LaunchImage-800-667h@2x.png
/path/to/Debug-iphonesimulator/Your.app/LaunchImage-700@2x.png
/path/to/Debug-iphonesimulator/Your.app/LaunchImage-700-568h@2x.png
/path/to/Debug-iphonesimulator/Your.app/LaunchImage-700-Landscape~ipad.png
/path/to/Debug-iphonesimulator/Your.app/LaunchImage-700-Landscape@2x~ipad.png

+[UIImage imageNamed:]Xcode 6.1.1 で使用してテスト済み。

于 2014-12-07T17:21:21.877 に答える