从nsbundle访问图像
我有一个框架试图从一个包中访问xib和图像。我能够访问xib,但无法加载UIImageView中的图像。我甚至检查文件是否存在,控制台输出是...从nsbundle访问图像
任何想法如何加载图像?
代码以在框架加载XIB的ViewController文件
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 /测试存在
您可以使用以下内容:
self.testImageView.image = [UIImage imageNamed:@"MyBundle.bundle/test.png"];
但似乎如果你把XIB在管束太,界面会相对于束。
self.testImageView.image = [UIImage imageNamed:@"test.png"]
如果图像已经在主束只需使用图像名称:test.png或简单地测试
[UIImage imageNamed:@"test.png"];
[UIImage imageNamed:@"test"];
如果+[UIImage imageNamed:]
不正确解析路径,你总是可以使用:
self.testImageView.image = [UIImage imageWithContentsOfFile: path];
没有'UIImage imageWithContentsOfPath:'这样的方法。 – rmaddy
不存在这样的方法.. –
请参阅,这是为什么不从内存中输入方法。这应该是+ [UIImage imageWithContentsOfFile]。自动更正真的让我的记忆受损。 –
当您使用imageNamed:
你必须通过只是一个简单的文件名和图像必须在应用程序的资源包的根目录中。
您的映像不在资源包的根目录中,它位于子文件夹中。
既然你已经在path
变量获得的图像的完整路径,则必须使用UIImage imageWithContentsOfFile:
方法:
self.testImageView.image = [UIImage imageWithContentsOfFile:path];
尝试了你的方法..没有工作... MyBundle.bundle是另一个包中的图像存在... 2 –
哪些不起作用?使用'imageWithContentsOfFile:'或使用替代方法从包中获取路径?用'imageWithContentsOfFile:'来使用你的路径应该可行。 – rmaddy
NSString * path = [[NSBundle mainBundle] pathForResource:@“test”ofType:@“png”inDirectory:@“MyBundle.bundle”]; self.testImageView2.image = [UIImage imageWithContentsOfFile:path]; 我试过这个......它没有工作...... –
尝试将一步一步来。
首先得到该路径捆绑你的主束内:
NSString *myBundlePath=[[NSBundle mainBundle] pathForResource:MyBundle ofType:@"bundle"];
检查,看是否存在捆绑任何东西。这是更多的双重检查。一旦它工作,您可以选择省略此代码。但是,仔细检查一下,总是一个好主意。
NSBundle *imageBundle=[NSBundle bundleWithPath: myBundlePath];
NSArray *allImageURLs=[imageBundle URLsForResourcesWithExtension:@"png" subdirectory:nil];
NSLog(@"imageURLS: %@",allImageURLS);
由于您已经拥有包路径,因此将图像名称添加到路径中。或者,您可以将其从上面代码中已有的网址列表中拉出。
NSString *myImagePath=[myBundlePath stringByAppendingPathComponent:@"test.png"];
NSLog(@"myImagePath=%@",myImagePath);
那么,既然你有完整的路径,加载图像从航运应用采取
UIImage *testImage = [UIImage imageWithContentsOfFile:backgroundImagePath];
代码。
好运
添
我想......它不工作... –
你只是试图@ “test.png”? –
y ...试过了...试过所有可能的组合 –