从iOS加载图像

Mat*_*oal 59 objective-c uiimage ios

我在项目中添加.bundle了一些填充了一些图像的文件夹.这是正确的参考这个图像直接写像?:

[UIImage imageNamed:@"imageInBundle.png"];
Run Code Online (Sandbox Code Playgroud)

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

Ign*_*ual 54

如果这不起作用,请尝试

[UIImage imageNamed:@"yourbundlefile.bundle/imageInBundle.png"];
Run Code Online (Sandbox Code Playgroud)

最好


Joe*_*Joe 50

这是正确的,imageNamed:将搜索你的主要包.项目中的图像,即使它们位于Project Navigator中的不同组中,也将位于主包中,可以通过名称直接访问.

  • 这仅在您的图像位于主包中时才有效。 (2认同)

小智 26

1)如果您正在使用bundle,请转到捆绑目标并将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];
Run Code Online (Sandbox Code Playgroud)


Jos*_*phH 20

感谢Apple在iOS 8中为此提供了适当的API imageNamed:inBundle:compatibleWithTraitCollection:.

它的使用方式如下:

[UIImage               imageNamed:@"image-name"
                         inBundle:[NSBundle bundleForClass:self.class]
    compatibleWithTraitCollection:nil]
Run Code Online (Sandbox Code Playgroud)

或者在swift中:

let image = UIImage(named: "image-name",
                    inBundle: NSBundle(forClass: self),
                    compatibleWithTraitCollection: nil)
Run Code Online (Sandbox Code Playgroud)


小智 7

此方法在xcode项目中的任何位置返回图像:=>

+(UIImage*)returnImageFromResourceBundle:(NSString*)nameOfImage
{
    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;
}
Run Code Online (Sandbox Code Playgroud)


osc*_*arr 6

迅捷3

let myImage = UIImage(named: "nameOfImage", in: Bundle(for: type(of: self)), compatibleWith: nil)
Run Code Online (Sandbox Code Playgroud)

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

Bundle(for: type(of: self))
Run Code Online (Sandbox Code Playgroud)


And*_*zie 5

因为我不得不为Swift解决这个问题,所以我想加上....

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

我在我的捆绑TestImage.png中的Supporting Files组中的位置.


Sur*_*gch 5

迅捷版

@AndrewMackenzie 的回答对我不起作用。这是什么工作

let image = UIImage(named: "imageInBundle.png")
imageView.image = image
Run Code Online (Sandbox Code Playgroud)

我的完整答案在这里


Pav*_*vic 5

对于Swift 3

let prettyImage = UIImage(named: "prettyImage",
            in: Bundle(for: self),
            compatibleWith: nil)
Run Code Online (Sandbox Code Playgroud)