方法1:使用定时器按时切换动画
//定义结构体,方块大小
CGRect frame=CGRectMake(13.5, 11.5, 22, 22);
//初始化图像视图对象,大小是frame
_musicImageView = [[UIImageView alloc] initWithFrame:frame];
_musicImageView.image = [UIImage imageNamed:@"music_la"];
//按照原始比例缩放图片,保持纵横比
_musicImageView.contentMode = UIViewContentModeScaleAspectFit;
//添加控件
[self addSubview:_musicImageView];
开始动画:
//加载动画
-(void)startNS {
__block NSString *str =@"music_la";
_musicImageView.image = [UIImage imageNamed:str];
//定时器开始执行的延时时间
NSTimeInterval delayTime = 0.0f;
//定时器间隔时间
NSTimeInterval timeInterval = 0.5f;
//创建子线程队列
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.5 * NSEC_PER_SEC);
dispatch_source_set_event_handler(_timer, ^{
//执行事件
if ( [str isEqualToString:@"music_la"]) {
str = @"music_lb";
} else if ( [str isEqualToString:@"music_lb"]){
str = @"music_lc";
}else if ( [str isEqualToString:@"music_lc"]){
str = @"music_ld";
}else if ( [str isEqualToString:@"music_ld"]){
str = @"music_la";
}
dispatch_async(dispatch_get_main_queue(), ^{
[_musicImageView setImage:[UIImage imageNamed:str]];
}) ;
});
// 启动计时器
dispatch_resume(_timer);
}
结束动画:
//停止动画
-(void)stopNS {
if (_timer) {
dispatch_source_cancel(_timer);
}
}
方法2: UIImageView 切换多张图片生成动画
//定义数组,存放所有图片对象
NSArray *images=[NSArray arrayWithObjects:[UIImage imageNamed:@"music_la"],[UIImage imageNamed:@"music_lb"],[UIImage imageNamed:@"music_lc"],[UIImage imageNamed:@"music_ld"], nil];
//定义结构体,方块大小
CGRect frame=CGRectMake(13.5, 11.5, 22, 22);
//初始化图像视图对象,大小是frame
_musicImageView = [[UIImageView alloc] initWithFrame:frame];
_musicImageView.image = [UIImage imageNamed:@"music_la"];
//imageView的动画图片是数组images
_musicImageView.animationImages = images;
//按照原始比例缩放图片,保持纵横比
_musicImageView.contentMode = UIViewContentModeScaleAspectFit;
//切换动作的时间3秒,来控制图像显示的速度有多快,
_musicImageView.animationDuration = 1.5;
//动画的重复次数,想让它无限循环就赋成0
_musicImageView.animationRepeatCount = 0;
//添加控件
[self addSubview:_musicImageView];
开始动画:
- (void)setPlayButtonView{
[self.musicImageView startAnimating];
}
结束动画:
- (void)setPauseButtonView{
[self.musicImageView stopAnimating];
}