逐帧动画

#import "ViewController.h"

@interface ViewController ()
{
    NSMutableArray *_imageArray;//存放动画的所有图片
    UIImageView *_imageView;
    UIImage *_image;
    
    
    CALayer *layer;
    int current;//记录加载的图片
    
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor blackColor];
    _imageArray =[[NSMutableArray alloc]initWithCapacity:10];
    _imageView.backgroundColor=[UIColor clearColor];
    [self imageViewFrame];
    [self layerFrame];
}

//使用uiimageview
- (void) imageViewFrame{
    _imageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 350, 298, 215)];
    [self.view addSubview:_imageView];
    // 加载所有图片
    for (int i=0; i<87; i++) {
        _image=[UIImage imageNamed:[NSString stringWithFormat:@"dazhao_%i",i+1]];
        [_imageArray addObject:_image];
    }
    //设置动画模式
    _imageView.animationImages=_imageArray;
    _imageView.animationDuration=0.1*[_imageArray count];
    _imageView.animationRepeatCount=HUGE_VALF;//重复次数
    [_imageView startAnimating];
}
//使用图层
- (void) layerFrame{
    layer=[[CALayer alloc]init];
    layer.frame=CGRectMake(0, 100, 298, 215);
    [self.view.layer addSublayer:layer];
    CADisplayLink *display=[CADisplayLink displayLinkWithTarget:self selector:@selector(step)];
    //添加时钟对象到主运行循环
    [display addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
}

- (void) step{
    static int s=0;
    s++;
    if (s%6==0) {
        UIImage *image=_imageArray[current];
        layer.contents=(id)image.CGImage;
        current=(current+1)%87;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


你可能感兴趣的:(逐帧动画)