我正在我的应用程序中显示一组图像。当我从资源文件夹加载图像时,代码可以正常工作,如下所示:
- (void)viewDidLoad
{
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:[NSString stringWithFormat: @"pic_a"]];
[array addObject:[NSString stringWithFormat: @"pic_b"]];
[array addObject:[NSString stringWithFormat: @"pic_c"]];
[array addObject:[NSString stringWithFormat: @"pic_d"]];
int index = arc4random() % [array count];
NSString *pictureName = [array objectAtIndex:index];
NSString* imagePath = [ [ NSBundle mainBundle] pathForResource:pictureName ofType:@"png"];
UIImage *img = [ UIImage imageWithContentsOfFile: imagePath];
if (img != nil) { // Image was loaded successfully.
[imageView setImage:img];
[imageView setUserInteractionEnabled:NO];
[img release]; // Release the image now that we have a UIImageView that contains it.
}
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
但是,如果我在“资源”组中创建一个“图像”组,并尝试从那里加载图像, View 中的图像将显示为空白。
[array addObject:[NSString stringWithFormat: @"images/pic_a"]];
[array addObject:[NSString stringWithFormat: @"images/pic_b"]];
[array addObject:[NSString stringWithFormat: @"images/pic_c"]];
[array addObject:[NSString stringWithFormat: @"images/pic_d"]];
我想将图像从 nib 文件和所有其他文件中分离出来。最好的方法是什么?
最佳答案
即使您将图像放在资源中的单独组中,您也可以通过调用名称来加载它们,例如使用这一行
UIImage *img = [UIImage imageNamed:[array objectAtIndex:index]];
代替这三行:
NSString *pictureName = [array objectAtIndex:index];
NSString* imagePath = [ [ NSBundle mainBundle] pathForResource:pictureName ofType:@"png"];
UIImage *img = [ UIImage imageWithContentsOfFile: imagePath];
您仍然可以简单地填充数组
[array addObject:[NSString stringWithFormat: @"pic_a"]];
如果您同时拥有 jpg 和 png 文件,则应将 .png
附加到文件名末尾。否则,将其关闭即可。
关于ios - 如何在 iOS 中将图像从资源中分离出来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7507119/