Reputation: 141
I have this piece of code I use to test animations in iOS. The goal is to load 4 png's and animate them in an UIImageView
. I have an NSMutableArray imageNames
in which I keep the paths to the images. It gets filled correctly. Then when I try to use it to create UIImage
it works the first time, but it returns nil afterwards. Why does this happen? I can't wrap my head around this.
for (NSInteger i = 0; i < imageNames.count; i++) {
NSString *name = [imageNames objectAtIndex:i];
[images addObject:[UIImage imageNamed:name]];
}
Here's the full code:
- (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];
}
Upvotes: 2
Views: 495
Reputation: 479
Well, as you said that it's for learning purposes I've tried your code and the only real problem I found is the one pointed by @rmaddy. I don't know where your image is stored exactly but I tried it adding 4 images as Assets and changed your code from this:
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];
}
to this:
// Load images
for (NSInteger i = 0; i < 4; i++) {
NSString *path = [NSString stringWithFormat:@"pos%i", i];
[imageNames addObject:path];
}
and I think it worked as you expected.
Upvotes: 1
Reputation: 31
Try to replace your
animationImageView.animationImages = images;
by this method:
[animationImageView setAnimationImagesWithUIImageViewSize:images];
This solution is provided by using this category: UIImageView+AnimationImages.m
Upvotes: 0