从nsbundle访问图像

我有一个框架试图从一个包中访问xib和图像。 我能够访问XIB罚款,但无法加载UIImageView中的图像。 我甚至检查文件是否存在,控制台输出是…

任何想法如何加载图像?

在框架viewcontroller文件中加载xib的代码

self = [super initWithNibName:@"ViewController_iPad" bundle:[NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"MyBundle" ofType:@"bundle"]]]; 

代码来加载图像

 - (void) loadImage { NSString *path = [[NSBundle mainBundle] pathForResource:@"MyBundle.bundle/test" ofType:@"png"]; BOOL present = NO; present = [[NSFileManager defaultManager] fileExistsAtPath:path]; if (present) { NSLog(@"MyBundle.bundle/test exists"); } else { NSLog(@"MyBundle.bundle/test does not exists"); } self.testImageView.image = [UIImage imageNamed:path]; self.testImageView2.image = [UIImage imageWithContentsOfFile:path]; } 

MyTestHarnessApp [11671:c07] MyBundle.bundle / test存在

当您使用imageNamed:您必须传递一个简单的文件名,并且该图像必须存在于应用程序资源包的根目录中。

您的映像不在资源包的根目录中,它位于子文件夹中。

由于您已经在pathvariables中获得了图像的完整path,所以您必须使用UIImage imageWithContentsOfFile:方法:

 self.testImageView.image = [UIImage imageWithContentsOfFile:path]; 

您可以使用以下内容:

 self.testImageView.image = [UIImage imageNamed:@"MyBundle.bundle/test.png"]; 

但是,如果你把XIB也放到了bundle中,接口将会和bundle相关。

 self.testImageView.image = [UIImage imageNamed:@"test.png"] 

如果+[UIImage imageNamed:]不能正确parsingpath,则可以始终使用:

 self.testImageView.image = [UIImage imageWithContentsOfFile: path]; 

尝试一步一步来。

首先得到你的主包中的包的path:

 NSString *myBundlePath=[[NSBundle mainBundle] pathForResource:MyBundle ofType:@"bundle"]; 

检查捆绑中是否有任何东西。 这是更多的双重检查。 一旦工作,您可以select省略此代码。 但是仔细检查一下,总是一个好主意。

  NSBundle *imageBundle=[NSBundle bundleWithPath: myBundlePath]; NSArray *allImageURLs=[imageBundle URLsForResourcesWithExtension:@"png" subdirectory:nil]; NSLog(@"imageURLS: %@",allImageURLS); 

由于您已经拥有包path,因此将图像名称添加到path中。 或者你可以把它从上面的代码中已经有的url列表中取出。

 NSString *myImagePath=[myBundlePath stringByAppendingPathComponent:@"test.png"]; NSLog(@"myImagePath=%@",myImagePath); 

然后,因为你有完整的path,加载图像

 UIImage *testImage = [UIImage imageWithContentsOfFile:backgroundImagePath]; 

代码取自航运应用程序。

祝你好运

蒂姆

如果图像已经在主包中,只需使用图像名称:test.png或简单地testing

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