我有这段代码用于测试iOS中的动画。目标是加载4个png并在UIImageView
中设置它们的动画。我有一个NSMutableArray imageNames
,其中我保留了图像的路径。它被正确填充。然后,当我尝试使用它创建UIImage
时,它第一次工作,但之后返回nil。为什么会这样?我无法绕过这个。
for (NSInteger i = 0; i < imageNames.count; i++) {
NSString *name = [imageNames objectAtIndex:i];
[images addObject:[UIImage imageNamed:name]];
}
这是完整的代码:
- (void)viewDidLoad
{
[super viewDidLoad];
UIView *test = [[UIView alloc] initWithFrame:CGRectMake(200, 200, 50, 50)];
test.backgroundColor = [UIColor purpleColor];
[self.view addSubview:test];
self.view.backgroundColor = [UIColor greenColor];
NSMutableArray *imageNames = [[NSMutableArray alloc] initWithCapacity:4];
NSString *basePath = @"/Users/johndoe/Desktop/soa/SoA/SoA/Models/firefly/";
// Load images
for (NSInteger i = 0; i < 4; i++) {
NSMutableString *fullPath = [NSMutableString stringWithString:basePath];
[fullPath appendFormat:@"SMALL_0000_Capa-%ld.png", i + 1];
[imageNames addObject:fullPath];
// [fullPath appendString:@"SMALL_0000_Capa-1.png"];
}
NSMutableArray *images = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < imageNames.count; i++) {
NSString *name = [imageNames objectAtIndex:i];
[images addObject:[UIImage imageNamed:name]];
}
// Normal Animation
UIImageView *animationImageView = [[UIImageView alloc] initWithFrame:CGRectMake(60, 95, 86, 193)];
animationImageView.animationImages = images;
animationImageView.animationDuration = 0.5;
[self.view addSubview:animationImageView];
[animationImageView startAnimating];
}
答案 0 :(得分:1)
好吧,正如你说的那样,为了学习目的,我已经尝试了你的代码,我找到的唯一真正的问题是@rmaddy指出的问题。我不知道你的图像存储的确切位置,但我尝试将4个图像添加为资产并从中更改了代码:
NSString *basePath = @"/Users/johndoe/Desktop/soa/SoA/SoA/Models/firefly/";
// Load images
for (NSInteger i = 0; i < 4; i++) {
NSMutableString *fullPath = [NSMutableString stringWithString:basePath];
[fullPath appendFormat:@"SMALL_0000_Capa-%ld.png", i + 1];
[imageNames addObject:fullPath];
}
到此:
// Load images
for (NSInteger i = 0; i < 4; i++) {
NSString *path = [NSString stringWithFormat:@"pos%i", i];
[imageNames addObject:path];
}
我认为它按预期工作。
答案 1 :(得分:0)
尝试更换
animationImageView.animationImages = images;
通过这种方法:
[animationImageView setAnimationImagesWithUIImageViewSize:images];
此解决方案使用此类别提供:UIImageView+AnimationImages.m