#import"ViewController.h"
@interfaceViewController()
@property(nonatomic,strong)CALayer*imageLayer;
@property(nonatomic,strong)dispatch_source_ttimer;
@property(nonatomic,strong)UIImageView*backImage;
@end
@implementationViewController
- (void)viewDidLoad {
[superviewDidLoad];
UIImageView*backImage = [[UIImageViewalloc]initWithFrame:CGRectMake(100,100,200,300)];
_backImage= backImage;
[self.viewaddSubview:backImage];
UIImage*image1 = [UIImageimageNamed:@"1"];
//创建出图片layer;
self.imageLayer= [CALayerlayer];
self.imageLayer.frame=CGRectMake(100,100,200,300);
[self.view.layeraddSublayer:self.imageLayer];
self.imageLayer.contents= (__bridgeid)(image1.CGImage);
[selfperformSelector:@selector(changeImages)withObject:nilafterDelay:1.0f];
}
-(void)changeImages {
__blockNSString*str =@"2";
self.backImage.image= [UIImageimageNamed:str];
//定时器开始执行的延时时间
NSTimeIntervaldelayTime =0.0f;
//定时器间隔时间
NSTimeIntervaltimeInterval =2.0f;
//创建子线程队列
dispatch_queue_tqueue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
//使用之前创建的队列来创建计时器
_timer=dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0, queue);
//设置延时执行时间,delayTime为要延时的秒数
dispatch_time_tstartDelayTime =dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime *NSEC_PER_SEC));
//设置计时器
dispatch_source_set_timer(_timer, startDelayTime, timeInterval *NSEC_PER_SEC,0.1*NSEC_PER_SEC);
dispatch_source_set_event_handler(_timer, ^{
//执行事件
if( [strisEqualToString:@"1"]) {
str =@"2";
}else{
str =@"1";
}
dispatch_async(dispatch_get_main_queue(), ^{
//图片动画;
CABasicAnimation*contentsAnimation = [CABasicAnimationanimationWithKeyPath:@"contents"];
contentsAnimation.fromValue=self.imageLayer.contents;
contentsAnimation.toValue= (__bridgeid)(self.backImage.image.CGImage);
contentsAnimation.duration=1;
//设定layer动画结束之后的值,(必须设定,否则会恢复到动画之前的状态)
self.imageLayer.contents= (__bridgeid)(self.backImage.image.CGImage);
//提交动画;
[self.imageLayeraddAnimation:contentsAnimationforKey:nil];
[self.backImagesetImage:[UIImageimageNamed:str]];
}) ;
});
//启动计时器
dispatch_resume(_timer);
}