使用iOS从捆绑软件加载图像

| 我在项目中添加了一个装有一些图像的“ 0”文件夹。 引用此图像直接写类似这样的图像是否正确:
[UIImage imageNamed:@\"imageInBundle.png\"];
哪种方法是访问和使用这些图像的最佳方法?     
已邀请:
没错,
imageNamed:
将搜索您的主捆绑包。项目中的图像,即使它们在项目导航器中位于不同的组中,也将位于您的主捆绑包中,并且可以通过名称直接访问。     
如果这样不起作用,请尝试
[UIImage imageNamed:@\"yourbundlefile.bundle/imageInBundle.png\"];
最好     
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];
    
值得庆幸的是,Apple从iOS 8开始为
imageNamed:inBundle:compatibleWithTraitCollection:
提供了适当的API。 它的用法如下:
[UIImage               imageNamed:@\"image-name\"
                         inBundle:[NSBundle bundleForClass:self.class]
    compatibleWithTraitCollection:nil]
或迅速:
let image = UIImage(named: \"image-name\",
                    inBundle: NSBundle(forClass: self),
                    compatibleWithTraitCollection: nil)
    
此方法在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;
}
    
迅捷3
let myImage = UIImage(named: \"nameOfImage\", in: Bundle(for: type(of: self)), compatibleWith: nil)
我无法获取当前的捆绑包,所以我这样做:
Bundle(for: type(of: self))
    
由于我必须为Swift弄清楚这一点,所以我想还要添加...。
if let imagePath = NSBundle.mainBundle().pathForImageResource(\"TestImage.png\")     
{
    imageView.image = NSImage(contentsOfFile: imagePath)
}
捆绑包中
Supporting Files
组中有
TestImage.png
的位置。     
对于Swift 3
let prettyImage = UIImage(named: \"prettyImage\",
            in: Bundle(for: self),
            compatibleWith: nil)
    
迅捷版 @AndrewMackenzie的答案对我没有帮助。这是起作用的
let image = UIImage(named: \"imageInBundle.png\")
imageView.image = image
我的完整答案在这里。     
如果要在同一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\"];
    

要回复问题请先登录注册