我有9张图片需要交叉淡入淡出。我尝试用imageview的animationImages方法做动画。但不幸的是,它不支持图像之间的交叉淡入淡出效果。有谁能告诉我如何实现这个目标?
答案 0 :(得分:4)
我通常使用Core Animation,特别是CABasicAnimation
,
我最近使用了这个,带有几个手势识别器的图像视图,用于左右滑动。看看我正在使用的褪色动画:
_someImageView = [[UIImageView alloc] initWithFrame:myFrame];
_someImageView.image = [myArrayOfImages objectAtIndex:0];
[self.view addSubview:_someImageView];
[_someImageView release];
_currentImageIndex = 0;
_someImageView.userInteractionEnabled = YES;
UISwipeGestureRecognizer *swipeLeftGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(changeImage:)];
swipeLeftGesture.direction = UISwipeGestureRecognizerDirectionLeft;
[_someImageView addGestureRecognizer:swipeLeftGesture];
[swipeLeftGesture release];
UISwipeGestureRecognizer *swipeRightGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(changeImage:)];
swipeRightGesture.direction = UISwipeGestureRecognizerDirectionRight;
[_someImageView addGestureRecognizer:swipeRightGesture];
[swipeRightGesture release];
然后每当我滑动时调用它,或者如果你喜欢做基于时间的事情,那么让你的计时器调用它,只需确保你增加一个计数器,以便你可以循环图像:
- (void)changeImage:(UISwipeGestureRecognizer *)swipe{
NSArray *images = [myArrayOfImages images];
NSInteger nextImageInteger = _currentImageIndex;
if(swipe.direction == UISwipeGestureRecognizerDirectionLeft)
nextImageInteger++;
else
nextImageInteger--;
if(nextImageInteger < 0)
nextImageInteger = images.count -1;
else if(nextImageInteger > images.count - 1)
nextImageInteger = 0;
_currentImageIndex = nextImageInteger;
UIImage *target = [images objectAtIndex:_currentImageIndex];
CABasicAnimation *crossFade = [CABasicAnimation animationWithKeyPath:@"contents"];
crossFade.duration = 0.5;
crossFade.fromValue = _someImageView.image;
crossFade.toValue = target;
[_someImageView.layer addAnimation:crossFade forKey:@"animateContents"];
_someImageView.image = target;
}
答案 1 :(得分:1)
只需创建两个图像视图并将它们叠放在一起。当您想要交叉渐变到下一个图像时,只需将底部图像视图的图像设置为要淡化到的图像,并将顶部图像视图的alpha设置为0.将其冲洗并重复。 / p>
答案 2 :(得分:0)
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
UIImage *img=[UIImage imageNamed:@"images.jpeg"];
imgview=[[UIImageView alloc]init];
imgview.frame=CGRectMake(30,90, img.size.width, img.size.height);
[self.view addSubview:imgview];
[self animateImages];
}
- (void)animateImages
{
static int count = 0;
NSArray *animationImages = @[[UIImage imageNamed:@"images.jpeg"], [UIImage imageNamed:@"images (1).jpeg"]];
UIImage *image = [animationImages objectAtIndex:(count % [animationImages count])];
[UIView transitionWithView:imgview
duration:2.0f // animation duration
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
imgview.image = image;
} completion:^(BOOL finished) {
[self animateImages];
count++;
}];
}