【问题标题】:Loading images for animation in UIImageView - iOS在 UIImageView 中加载动画图像 - iOS
【发布时间】:2013-05-13 03:29:09
【问题描述】:

我要为动画加载大约 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 尝试过,但无法弄清楚。

【问题讨论】:

标签: ios objective-c uiimageview uiimage nsarray


【解决方案1】:

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

- (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];
}

【讨论】:

  • 你在strImageName中有一个空格@"loading %4d.png应该是@loading%4d.png"
  • 应该是 [NSString stringWithFormat:@"loading%03d.png", i];
  • 感谢所有工作。我曾尝试过类似的事情,但被困在loading%03.png
  • 使用 UIImageView.animationImages 很快就会使您的设备崩溃。很多人遇到这个问题,真正的解决方案是不使用 UIImageView 来做动画。
  • @MoDJ 我已将上面的代码用于最多 20 个图像动画,我同意您的观点,应用程序可能会崩溃,感谢您的链接。 +1 用于挖掘旧问题
【解决方案2】:

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

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

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

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

即不用0填充。

animatedImageNamed 函数从 iOS 5.0 开始提供。

【讨论】:

  • 如何停止这个动画?你有什么想法吗?
  • @yucelbayram 必须在动画图像上设置才能使重复计数生效。可以设置完成时的最后一张图像。 stackoverflow.com/questions/29621400/…
【解决方案3】:

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

【讨论】:

  • 我的图片很小,所以要使用图片动画。
【解决方案4】:

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

【讨论】:

    猜你喜欢
    • 2016-06-04
    • 2011-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多