ios - 如何在 iOS 中将图像从资源中分离出来

标签 ios resources

我正在我的应用程序中显示一组图像。当我从资源文件夹加载图像时,代码可以正常工作,如下所示:

- (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/

相关文章:

ios - mergAccessory ios external 是否仅适用于打印机?

css - 如何在 Hippo CMS 中包含 CSS 文件?

android - 从互联网下载 Android 布局

visual-studio-2010 - Visual Studio 2010 本地化资源文件,如何自动添加字符串?

azure - 如何获取 Terraform 中的资源组列表

ios - 如果使用 "ActiveLabel.swift"标记单词有空格,它将标记失败 - swift

objective-c - 如何从 NSOperation 获取对 NSOperationQueue 的引用?

php - 无效的 JSON 需要 Swift iOS

ios - 每次打开项目时 Xcode 都会意外退出

java - 耶拿 - 如何将资源链接到属性?