4

我要为动画加载大约 300 张图像,这些图像被命名为loading001.png, loading002.png, loading003.png, loading004.png………loading300.png

我正在按照以下方式进行操作。

.h 文件

    #import <UIKit/UIKit.h>
    @interface CenterViewController : UIViewController  {
        UIImageView *imgView;
    }

    @end

.m 文件

@implementation CenterViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    imgView = [[UIImageView alloc] init];
    imgView.animationImages = [[NSArray alloc] initWithObjects:
                               [UIImage imageNamed:@"loading001.png"],
                               [UIImage imageNamed:@"loading002.png"],
                               [UIImage imageNamed:@"loading003.png"],
                               [UIImage imageNamed:@"loading004.png"],
                               nil];
}

- (IBAction)startAnimation:(id)sender{
    [imgView startAnimating];
}

@end

有没有一种有效的方法将图像加载到数组中。我曾尝试过,for loop但无法弄清楚。

4

4 回答 4

16

您可以尝试以下代码以更好的方式将图像加载到数组中

- (void)viewDidLoad {
    [super viewDidLoad];

    NSMutableArray *imgListArray = [NSMutableArray array];
    for (int i=1; i <= 300; i++) {
        NSString *strImgeName = [NSString stringWithFormat:@"loading%03d.png", i];
        UIImage *image = [UIImage imageNamed:strImgeName];
            if (!image) {
                NSLog(@"Could not load image named: %@", strImgeName);
            }
            else {
                [imgListArray addObject:image];
            }
        }
    imgView = [[UIImageView alloc] init];
    [imgView setAnimationImages:imgListArray];
}
于 2013-05-17T21:07:00.927 回答
3

有一种更简单的方法可以做到这一点。您可以简单地使用:

[UIImage animatedImageNamed:@"loading" duration:1.0f]

1.0f为所有图像设置动画的持续时间在哪里。但是,要使其正常工作,您的图像必须像这样命名:

loading1.png
loading2.png
.
.
loading99.png
.
.
loading300.png

也就是说,没有用 0 填充。

该功能animatedImageNamed从 iOS 5.0 开始可用。

于 2015-05-18T06:06:44.053 回答
2

根据图像的大小,300 幅图像动画序列可能会占用大量内存。使用电影可能是更好的解决方案。

于 2013-05-17T21:11:47.500 回答
2

您的代码在设备上运行时会崩溃,在 iOS 上无法将这么多图像解压缩到内存中。您将收到内存警告,然后您的应用程序将被操作系统杀死。有关不会在设备上崩溃的解决方案,请参阅我对how-to-do-animations-using-images-efficiently-in-ios 的回答。

于 2013-06-20T22:59:39.650 回答