我需要在我的应用程序中设置UIImageView动画,并循环更改其中的UIImage,使其看起来像动画照片幻灯片。
现在我正在使用NSTimer来每隔N
秒触发UIImage更改和动画本身:
- (void)viewDidLoad {
// NSArray initialization
NSTimer *timer = [NSTimer timerWithTimeInterval:16
target:self
selector:@selector(onTimer)
userInfo:nil
repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
[timer fire];
[super viewDidLoad];
}
这是onTimer
选择器代码:
- (void) onTimer {
// cycle through max 9 images
if(imageIndex > 8)
imageIndex = 0;
// set the image
[_imageContainer setImage:[images objectAtIndex:imageIndex]];
// reset width and height of the UIImage frame
CGRect frame = [_imageContainer frame];
frame.size.width -= 170.0f;
frame.size.height -= 100.0f;
[_imageContainer setFrame:frame];
// fade in
[UIView animateKeyframesWithDuration:2.0f delay:0.0f options:0 animations:^{
[_imageContainer setAlpha:1];
} completion:^(BOOL finished) {
// image movement
[UIView animateKeyframesWithDuration:12.0f delay:0.0f options:0 animations:^{
CGRect frame = [_imageContainer frame];
frame.size.width += 170.0f;
frame.size.height += 100.0f;
[_imageContainer setFrame:frame];
} completion:^(BOOL finished) {
// fade out
[UIView animateKeyframesWithDuration:2.0f delay:0.0f options:0 animations:^{
[_imageContainer setAlpha:0];
} completion:nil];
}];
}];
imageIndex++;
}
这似乎是一种非常原始但却“有效”的方式来实现我想要的但我认识到它可能不是理想的方式。
有没有更好的方法来实现我正在寻找的东西?
答案 0 :(得分:0)
更新了淡入淡出动画的答案
- (void)viewDidLoad
{
[super viewDidLoad];
// self.animationImages is your Image Array
self.animationImages = @[[UIImage imageNamed:@"Image1"], [UIImage imageNamed:@"Image2"]];
// make the first call
[self animateImages];
}
- (void)animateImages
{
static int count = 0;
UIImage *image = [self.animationImages objectAtIndex:(count % [animationImages count])];
[UIView transitionWithView:self.animationImageView
duration:1.0f // animation duration
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
self.animationImageView.image = image; // change to other image
} completion:^(BOOL finished) {
[self animateImages]; // once finished, repeat again
count++; // this is to keep the reference of which image should be loaded next
}];
}