你的位置:首页 > 操作系统

[操作系统]UIImageView 自带动画+N张图片实现很炫的动画


gitHub上又看到个很炫的动画:https://github.com/MartinRGB/GiftCard-iOS
 
看了看他的代码,发现核心动画(就是把按钮包装成一个礼物盒)其实很简单,就是把一个动画的一帧一帧都截取下来放到一个数组里面,然后利用了UIImageView自带的可以播放一个image的数组的方法。
简化过的代码大概是这样子:
 
- (void)viewDidLoad {
    [super viewDidLoad];
 
    NSMutableArray *array = [NSMutableArray array];
    for (int i = 0; i < 40; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat: @"gifbutton000%02d",i]];
        [array addObject:image];
    }
    self.giftImageArray = array;
    self.giftImageView.animationDuration = 1.0;
    self.giftImageView.animationImages = self.giftImageArray;
    self.giftImageView.animationRepeatCount = 1;
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGiftImageViewTapped:)];
    [self.giftImageView addGestureRecognizer:tapGesture];
    self.giftImageView.userInteractionEnabled = YES;
    self.giftImageView.image = [self.giftImageArray firstObject];
   
}
 
- (void)handleGiftImageViewTapped:(UITapGestureRecognizer *)sender {
    [self.giftImageView startAnimating];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        UIImage *image =  [self.giftImageArray lastObject];
        self.giftImageView.image = image;
    });
}
效果如图:

 
 
方法虽然简单,但是效果很赞,不知道有没有更好的实现方式,但这起码是一种实现方式,值得记录一下!