给UIImageView设置一组图片动画,每张图片停留时间不一祥

来源:互联网 发布:纱裙布料淘宝 编辑:程序博客网 时间:2024/04/30 03:31

一组图片
给UIView 写个分类

//UIView+KeyFrameAnimation.h#import <UIKit/UIKit.h>@interface UIView (KeyFrameAnimation)- (void)addAnimationWithImages:(NSArray *)animationImages                         times:(NSArray *)times                   repeatCount:(float)count                animationFrame:(CGRect)frame;@end
//  UIView+KeyFrameAnimation.m#import "UIView+KeyFrameAnimation.h"@implementation UIView (KeyFrameAnimation)- (void)addAnimationWithImages:(NSArray *)animationImages times:(NSArray *)times repeatCount:(float)count animationFrame:(CGRect)frame{    NSArray *sumArray = [self sumWithArray:times];//前几个的和;    NSTimeInterval total = [[sumArray lastObject] doubleValue];    NSMutableArray  *keyTimes = [NSMutableArray arrayWithObjects:@0.0f, nil];    for (NSNumber *time in sumArray) {        NSTimeInterval timeFloat = [time floatValue] / total;        [keyTimes addObject:[NSNumber numberWithDouble:timeFloat]];    }    [keyTimes addObject:@1.0f];    //CAImage 数组    NSMutableArray *array = [NSMutableArray array];    for (UIImage *image in animationImages) {        CGImageRef cgImage = [image CGImage];        [array addObject:(__bridge id _Nonnull)(cgImage)];    }    CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];    animation.calculationMode = kCAAnimationDiscrete;    animation.keyPath = @"contents";    animation.duration = total;    animation.delegate = self;    animation.repeatCount = count;    animation.values = array;    animation.keyTimes = keyTimes;//每帧比例相对1的比例时间数组[0...1]    CALayer *layer = [CALayer layer];    layer.frame = frame;    [layer addAnimation:animation forKey:nil];    [self.layer addSublayer:layer];}-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{    [[self.layer.sublayers lastObject] removeFromSuperlayer];}-(NSArray *)sumWithArray:(NSArray*)array{    NSMutableArray *mutableArray = [NSMutableArray array];    double sum = 0;    for (int i = 0; i < array.count; i++) {        sum += [((NSNumber *)array[i]) floatValue];        [mutableArray addObject:[NSNumber numberWithFloat:sum]];    }    return mutableArray;}@end

调用

-(void)animation{    NSArray *imagePaths = [[NSBundle mainBundle] pathsForResourcesOfType:@"png" inDirectory:@"animations"];    NSMutableArray *animationImages = [NSMutableArray array];    NSArray* times = @[@0.7, @0.4, @0.3, @0.5, @0.4, @0.4, @0.4, @0.8];    for (NSString *imageName in imagePaths) {        [animationImages addObject:[UIImage imageNamed:imageName]];    }    [self.imageView addAnimationWithImages:animationImages times:times repeatCount:1 animationFrame:CGRectMake(0, 0, image.size.width, image.size.height)];}
0 0
原创粉丝点击