使用 iOS 从捆绑包中加载图像

发布于 2024-11-01 07:25:03 字数 155 浏览 5 评论 0原文

我在项目中添加了一个 .bundle 文件夹,其中填充了一些图像。 直接引用此图像是否正确,写类似?:

[UIImage imageNamed:@"imageInBundle.png"];

访问和使用这些图像的最佳方法是什么?

I added to my project a .bundle folder filled with some images.
Is it correct refer to this image directly writing something like ?:

[UIImage imageNamed:@"imageInBundle.png"];

Which is the best method to access and use these images ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

删除→记忆 2024-11-08 07:25:03

是的,imageNamed: 将搜索您的主包。项目中的图像,即使它们位于项目导航器中的不同组中,也将位于您的主包中,并且可以通过名称直接访问。

That is correct, imageNamed: will search your main bundle. Images in your project, even if they are in different groups in your Project Navigator will be in your main bundle and can be accessed directly by name.

甜`诱少女 2024-11-08 07:25:03

如果这不起作用,请尝试

[UIImage imageNamed:@"yourbundlefile.bundle/imageInBundle.png"];

最佳

If that does not work, try

[UIImage imageNamed:@"yourbundlefile.bundle/imageInBundle.png"];

Best

守护在此方 2024-11-08 07:25:03

值得庆幸的是,从 iOS 8 开始,Apple 已经为此提供了适当的 API,imageNamed:inBundle:companyWithTraitCollection:

它的使用方式如下:

[UIImage               imageNamed:@"image-name"
                         inBundle:[NSBundle bundleForClass:self.class]
    compatibleWithTraitCollection:nil]

或在 swift:

let image = UIImage(named: "image-name",
                    inBundle: NSBundle(forClass: type(of:self)),
                    compatibleWithTraitCollection: nil)

或在 swift 5 中:

let image = UIImage(named: "image-name",
                    in: Bundle(for: type(of:self)),
                    compatibleWith: nil)

Apple has thankfully provided a proper API for this from iOS 8 onwards, imageNamed:inBundle:compatibleWithTraitCollection:.

It's used like so:

[UIImage               imageNamed:@"image-name"
                         inBundle:[NSBundle bundleForClass:self.class]
    compatibleWithTraitCollection:nil]

or in swift:

let image = UIImage(named: "image-name",
                    inBundle: NSBundle(forClass: type(of:self)),
                    compatibleWithTraitCollection: nil)

or in swift 5:

let image = UIImage(named: "image-name",
                    in: Bundle(for: type(of:self)),
                    compatibleWith: nil)
梦魇绽荼蘼 2024-11-08 07:25:03

1) 如果您正在使用捆绑包,请转到捆绑包目标并将 COMBINE_HIDPI_IMAGES 设置为 NO。
在另一种情况下,图像将转换为 tiff 格式。

2)尝试这个代码:

NSBundle *bundle = [NSBundle bundleWithURL:[[NSBundle mainBundle] URLForResource:@"YourBundle" withExtension:@"bundle"]];
NSString *imagePath = [bundle pathForResource:@"imageInBundle" ofType:@"png"];
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];

1) If you are working with bundles go to bundle target and set COMBINE_HIDPI_IMAGES to NO.
In another case the image will be converted to tiff format.

2) try this code:

NSBundle *bundle = [NSBundle bundleWithURL:[[NSBundle mainBundle] URLForResource:@"YourBundle" withExtension:@"bundle"]];
NSString *imagePath = [bundle pathForResource:@"imageInBundle" ofType:@"png"];
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
汹涌人海 2024-11-08 07:25:03

Swift 3

let myImage = UIImage(named: "nameOfImage", in: Bundle(for: type(of: self)), compatibleWith: nil)

我无法获取当前捆绑包,所以我这样做:

Bundle(for: type(of: self))

Swift 3

let myImage = UIImage(named: "nameOfImage", in: Bundle(for: type(of: self)), compatibleWith: nil)

I can't get current bundle so i do this:

Bundle(for: type(of: self))
油饼 2024-11-08 07:25:03

您需要执行以下步骤:

  • 将图像文件添加到您的 Xcode 项目中:
  • 首先,确保您拥有要在项目中使用的图像文件。将它们拖放到您的 Xcode 项目中,确保它们添加到适当的目标。
  • 创建资源包:
  • 接下来,您将创建一个包含图像的资源包。
    为此,请按照下列步骤操作: 在 Xcode 中,转到“文件”->“文件”。新->
    目标。在模板选择对话框中选择“iOS”或“macOS”。
    向下滚动并从模板列表中选择“捆绑包”。点击
    “下一步”并为您的包命名(例如“ImageResourcesBundle”)。
  • 确保目标已添加到您的主应用程序目标中。添加
    图像文件到捆绑包:
  • 创建捆绑包后,请确保将图像文件添加到
    捆绑包的目标。为此,请在 Xcode 项目中选择捆绑包
    导航器,然后将图像文件拖放到包中
    “复制捆绑资源”构建阶段。
  • 从资源包中加载图像:最后,您可以加载
    使用适当的 Bundle 方法从资源包中获取图像。

下面是如何执行此操作的示例:

Swift 代码

**

func getImageFromResourceBundle(named imageName: String) -> UIImage? {
    // Replace "ImageResourcesBundle" with the name of your resource bundle.
    guard let bundleURL = Bundle.main.url(forResource: "ImageResourcesBundle", withExtension: "bundle"),
          let resourceBundle = Bundle(url: bundleURL) else {
        return nil
    }
    
    // Load the image from the resource bundle.
    return UIImage(named: imageName, in: resourceBundle, compatibleWith: nil)
}

Objective C 代码

+(UIImage*) getImageFromResourceBundle:(NSString*) imageName
{
    NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"Resource" ofType:@"bundle"];
    NSString *imageString = [[NSBundle bundleWithPath:bundlePath] pathForResource:nameOfImage ofType:@"png"];
    
    UIImage *retrievedImage = [[UIImage alloc] initWithContentsOfFile: imageString];
    return retrievedImage;
}

然后您可以调用此函数从资源包中获取图像:

if let image = getImageFromResourceBundle(named: "imageName") {
    // Do something with the image.
} else {
    // The image couldn't be loaded.
}

You'll need to follow these steps:

  • Add the image files to your Xcode project:
  • First, make sure you have the image files you want to use in your project. Drag and drop them into your Xcode project, ensuring they are added to the appropriate target.
  • Create a resource bundle:
  • Next, you'll create a resource bundle that will contain the images.
    To do this, follow these steps: In Xcode, go to File -> New ->
    Target. Select "iOS" or "macOS" in the template selection dialog.
    Scroll down and choose "Bundle" from the list of templates. Click
    "Next" and give your bundle a name (e.g., "ImageResourcesBundle").
  • Ensure that the target is added to your main app target. Add the
    image files to the bundle:
  • After creating the bundle, make sure to add the image files to the
    bundle's target. To do this, select the bundle in Xcode's project
    navigator, and then drag and drop the image files into the bundle's
    "Copy Bundle Resources" build phase.
  • Load the image from the resource bundle: Finally, you can load the
    image from the resource bundle using the appropriate Bundle method.

Below is an example of how to do it:

Swift Code

**

func getImageFromResourceBundle(named imageName: String) -> UIImage? {
    // Replace "ImageResourcesBundle" with the name of your resource bundle.
    guard let bundleURL = Bundle.main.url(forResource: "ImageResourcesBundle", withExtension: "bundle"),
          let resourceBundle = Bundle(url: bundleURL) else {
        return nil
    }
    
    // Load the image from the resource bundle.
    return UIImage(named: imageName, in: resourceBundle, compatibleWith: nil)
}

Objective C Code

+(UIImage*) getImageFromResourceBundle:(NSString*) imageName
{
    NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"Resource" ofType:@"bundle"];
    NSString *imageString = [[NSBundle bundleWithPath:bundlePath] pathForResource:nameOfImage ofType:@"png"];
    
    UIImage *retrievedImage = [[UIImage alloc] initWithContentsOfFile: imageString];
    return retrievedImage;
}

You can then call this function to get the image from the resource bundle:

if let image = getImageFromResourceBundle(named: "imageName") {
    // Do something with the image.
} else {
    // The image couldn't be loaded.
}
坦然微笑 2024-11-08 07:25:03

Swift 版本

@AndrewMackenzie 的回答对我不起作用。这就是有效的方法

let image = UIImage(named: "imageInBundle.png")
imageView.image = image

我的完整答案在这里

Swift version

@AndrewMackenzie's answer didn't work me. This is what did work

let image = UIImage(named: "imageInBundle.png")
imageView.image = image

My full answer is here.

平定天下 2024-11-08 07:25:03

由于我必须为 Swift 解决这个问题,我想我还要添加......

if let imagePath = NSBundle.mainBundle().pathForImageResource("TestImage.png")     
{
    imageView.image = NSImage(contentsOfFile: imagePath)
}

我的包内的 Supporting Files 组中有 TestImage.png

Since I had to figure this out for Swift, thought I would add also....

if let imagePath = NSBundle.mainBundle().pathForImageResource("TestImage.png")     
{
    imageView.image = NSImage(contentsOfFile: imagePath)
}

Where I have TestImage.png in the Supporting Files group inside my bundle.

半城柳色半声笛 2024-11-08 07:25:03

对于斯威夫特 3

let prettyImage = UIImage(named: "prettyImage",
            in: Bundle(for: self),
            compatibleWith: nil)

For Swift 3

let prettyImage = UIImage(named: "prettyImage",
            in: Bundle(for: self),
            compatibleWith: nil)
深海夜未眠 2024-11-08 07:25:03

如果您要在同一个 viewController 中多次使用它,有一种快速方法:

在与以下方法相同的类中的任何位置获取图像:

// this fetches the image from: MyBundle.bundle/folder/to/images/myImage.png
UIImage *myImage = [self imageFromBundle:@"MyBundle" withPath:@"folder/to/images/myImage.png"];

获取图像的方法:

- (UIImage *)imageFromBundle:(NSString *)bundleName withPath:(NSString *)imageName
{
    NSURL *bundleURL = [[NSBundle mainBundle] URLForResource:bundleName withExtension:@"bundle"];
    NSBundle *bundle = [NSBundle bundleWithURL:bundleURL];
    NSString *imagePath = [bundle pathForResource:imageName ofType:nil];
    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
    return image;
}

或者直接从捆绑包中调用它:

UIImage *myImage = [UIImage imageNamed:@"MyBundle.bundle/folder/to/images/myImage.png"];

A quick way to do it if you are going to use it a couple of times in the same viewController:

Get the image anywhere in the same class as the method below:

// this fetches the image from: MyBundle.bundle/folder/to/images/myImage.png
UIImage *myImage = [self imageFromBundle:@"MyBundle" withPath:@"folder/to/images/myImage.png"];

Method that fetches the image:

- (UIImage *)imageFromBundle:(NSString *)bundleName withPath:(NSString *)imageName
{
    NSURL *bundleURL = [[NSBundle mainBundle] URLForResource:bundleName withExtension:@"bundle"];
    NSBundle *bundle = [NSBundle bundleWithURL:bundleURL];
    NSString *imagePath = [bundle pathForResource:imageName ofType:nil];
    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
    return image;
}

Or simply call it straight out of the bundle:

UIImage *myImage = [UIImage imageNamed:@"MyBundle.bundle/folder/to/images/myImage.png"];
鯉魚旗 2024-11-08 07:25:03

如果您正在构建一个框架,并且希望 UIImage(named: "image") 的所有实例始终使用您的自定义包,您可以创建一个如下所示的扩展来覆盖它

// Swift 5

extension UIImage {
  convenience init?(named: String) {
    self.init(named: named, in: <#Your Bundle#>, compatibleWith: nil)
  }
}

If you are building a framework and you would like all instances of UIImage(named: "image") to always use your custom bundle, you can make an extension like below that will override it

// Swift 5

extension UIImage {
  convenience init?(named: String) {
    self.init(named: named, in: <#Your Bundle#>, compatibleWith: nil)
  }
}
羁〃客ぐ 2024-11-08 07:25:03

我在尝试解决从 Swift Package 加载图像时发现了这个问题,所以如果其他人也遇到这个问题,这就是我解决它的方法:

let image = UIImage(named: "imageName", in: Bundle.module,兼容:无)

I found this question when trying to solve loading images from Swift Package, so if anybody else is struggling with that as well here's how I solved it:

let image = UIImage(named: "imageName", in: Bundle.module, compatibleWith: nil)

っ〆星空下的拥抱 2024-11-08 07:25:03

这在 Swift 5 中对我有用

// Empty UIImage array to store the images in it.
var icons = [UIImage]()

let fileManager = FileManager.default
let bundleURL = Bundle.main.bundleURL
let assetURL = bundleURL.appendingPathComponent("MyBundle.bundle") // Bundle URL
do {
  let contents = try fileManager.contentsOfDirectory(at: assetURL,
 includingPropertiesForKeys: [URLResourceKey.nameKey, URLResourceKey.isDirectoryKey],
 options: .skipsHiddenFiles)
  for item in contents { // item is the URL of everything in MyBundle imgs or otherwise.

      let image = UIImage(contentsOfFile: item.path) // Initializing an image
      icons.append(image!) // Adding the image to the icons array
  }
}
catch let error as NSError {
  print(error)
}

This is worked for me in Swift 5

// Empty UIImage array to store the images in it.
var icons = [UIImage]()

let fileManager = FileManager.default
let bundleURL = Bundle.main.bundleURL
let assetURL = bundleURL.appendingPathComponent("MyBundle.bundle") // Bundle URL
do {
  let contents = try fileManager.contentsOfDirectory(at: assetURL,
 includingPropertiesForKeys: [URLResourceKey.nameKey, URLResourceKey.isDirectoryKey],
 options: .skipsHiddenFiles)
  for item in contents { // item is the URL of everything in MyBundle imgs or otherwise.

      let image = UIImage(contentsOfFile: item.path) // Initializing an image
      icons.append(image!) // Adding the image to the icons array
  }
}
catch let error as NSError {
  print(error)
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文