繁体   English   中英

如何在iOS中从资源中分离出图像

[英]How to separate images out from Resources in 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.
}

但是,如果我在“资源”组中创建一个“图像”组,并尝试从那里加载图像,则视图中的图像将显示为空白。

[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 否则,将其保留就可以了。

尝试使用imageNamed:方法代替imageWithContentsOfFile:

请记住,在项目内部添加组仅是为了组织和在Xcode中查看。 您添加组不会更改将图像保存在主捆绑包中的事实。 如果您尝试使用字符串中的images组找到它们,则不会找到它们。

您可以做一些事情来完成这项工作,但实际上您不需要这样做。

您需要创建一个名为images的物理文件夹(它应该具有蓝色而不是通常的黄色)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM