在开发中我们有可能会遇到这样的需求,在一个UIImageView来回切换俩张图片来达到动态效果。我也是实验了好久,后来经过指导实现了,效果如下:
iOS中定时器有三种:(1)NSTimer (2)CADisplayLink (3)dispatch_source,而我使用到的定时器是dispatch_source,下面就来看看代码吧。(可以实现暂停和播放)
//初始化UIImageView
UIImage *img = [UIImage imageNamed:@"image_huoyan_1"];
backImage = [[UIImageView alloc] initWithFrame:CGRectMake(50, 60, self.view.frame.size.width/5, self.view.frame.size.width/5 * img.size.height/img.size.width)];
[backImage setImage:img];
[self.view addSubview:backImage];
//加载按钮
self.button = [UIButton buttonWithType:UIButtonTypeCustom];
self.button.frame = CGRectMake(100, 300, 100, 100);
self.button.backgroundColor = [UIColor blueColor];
[self.button addTarget:self action:@selector(isAnimotion) forControlEvents:UIControlEventTouchUpInside];
[self.button setTitle:@"开始" forState:UIControlStateNormal];
[self.view addSubview:self.button];
//按钮的点击事件
-(void)isAnimotion {
if([self.button.titleLabel.text isEqualToString:@"停止"]) {
[self stopNS];
[self.button setTitle:@"开始" forState:UIControlStateNormal];
} else {
[self startNS];
[self.button setTitle:@"停止" forState:UIControlStateNormal];
}
}
接下来就是主要代码啦,其中需要注意的是:需要将dispatch_source_t timer
设置为成员变量,不然会立即释放。
@property (nonatomic, strong) dispatch_source_t timer;
//加载动画
-(void)startNS {
__block NSString *str =@"image_huoyan_2";
backImage.image = [UIImage imageNamed:str];
//定时器开始执行的延时时间
NSTimeInterval delayTime = 0.0f;
//定时器间隔时间
NSTimeInterval timeInterval = 0.1f;
//创建子线程队列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//使用之前创建的队列来创建计时器
_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
//设置延时执行时间,delayTime为要延时的秒数
dispatch_time_t startDelayTime = 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 ( [str isEqualToString:@"image_huoyan_1"]) {
str = @"image_huoyan_2";
} else {
str = @"image_huoyan_1";
}
dispatch_async(dispatch_get_main_queue(), ^{
[backImage setImage:[UIImage imageNamed:str]];
}) ;
});
// 启动计时器
dispatch_resume(_timer);
}
//停止动画
-(void)stopNS {
dispatch_source_cancel(_timer);
}
上面提到的"image_huoyan_1"和"image_huoyan_2"就是要用到的俩张图片。写的比较简单,如果有错误请多多指教。