如何在UIImageView上创建从一个图像到另一个图像的淡入效果?

时间:2014-07-01 21:29:31

标签: ios animation uiimageview uiviewanimationtransition

您好我有以下代码尝试淡入和淡出我的imageview图像:

- (void)oneFingerSwipeLeft:(UITapGestureRecognizer *)recognizer {
// Insert your own code to handle swipe left
[imageview setAlpha:0];
[UIImageView beginAnimations:NULL context:nil];
[UIImageView setAnimationCurve:UIViewAnimationCurveEaseIn];
[UIImageView setAnimationDuration:1];
[imageview setAlpha:1];
[UIImageView commitAnimations];
imageview.image = [UIImage imageNamed:@"image1.jpg"];
}

- (void)oneFingerSwipeRight:(UITapGestureRecognizer *)recognizer {
// Insert your own code to handle swipe right
[imageview setAlpha:0];
[UIImageView beginAnimations:NULL context:nil];
[UIImageView setAnimationCurve:UIViewAnimationCurveEaseIn];
[UIImageView setAnimationDuration:1];
[imageview setAlpha:1];
[UIImageView commitAnimations];
imageview.image = [UIImage imageNamed:@"image2.jpg"];

然而,这样做有点以某种方式闪现图像,如何从一个图像到另一个图像进行平滑的淡入/淡出过渡?

此外,我有图像image1,image2,image3等。 每次刷卡时,我如何进行从图像1到2到3的转换?

2 个答案:

答案 0 :(得分:3)

首先,不要使用“旧式”'动画。来自Apple docs

  

在iOS 4.0及更高版本中不鼓励使用此方法。你应该用   基于块的动画方法来指定你的动画。

要在2个imageViews之间淡入淡出,请尝试以下方法:

@property (strong, nonatomic) UIImageView * myImageView;

- (void) fadeToImage: (UIImage *) newImage
{
    // First create a new imageView in the same place as the current one
    UIImageView * newImageView = [[UIImageView alloc] initWithFrame: self.myImageView.frame];
    newImageView.image = newImage;
    newImageView.alpha = 0.0;
    [self.myImageView.superview insertSubview: newImageView aboveSubview: self.myImageView];

    [UIView animateWithDuration: 1.0
                     animations:^{

                         // Cross-fade the images
                         newImageView.alpha = 1.0;
                         self.myImageView.alpha = 0.0;
                     }
                     completion:^(BOOL finished) {
                         // Finally remove the old imageView and replace with the new
                         [self.imageView removeFromSuperview];
                         self.myImageView = newImageView;
                     }];
}

答案 1 :(得分:-1)

进行适当的交叉溶解是一项更多的工作,但并不多。首先,您需要三个视图,父视图和两个子视图。父视图可以是通用UIView(在下面的代码中,我使用视图控制器的主视图作为父视图)。这两个孩子是UIImageView个,是父视图的子视图。孩子应该有相同的frame s,但孩子们不必与父母一样大。

最初,currentImageView的{​​{1}}属性设置为hiddenNO的{​​{1}}属性设置为nextImageView }。转换代码如下所示。

hidden

YES块中的指针交换允许您只需更改[UIView transitionWithView:self.view duration:1.0 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{ self.nextImageView.hidden = NO; self.currentImageView.hidden = YES; } completion:^(BOOL finished) { UIImageView *temp = self.currentImageView; self.currentImageView = self.nextImageView; self.nextImageView = temp; } ]; 的{​​{1}}属性即可进行下一次转换,然后再次运行转换。