iOS UIButton设置图片动画

1.问题描述:实现点击按钮播放MP3音频并开启动画,再点击按钮关闭动画以及音频

效果类似以下(图片来自网络,侵删),动画效果其实就是几张连续的图片组成:

2.实现思路

2.1 自定义view,设置imageview的动画以及添加view的点击手势控制动画播放、结束;

2.2 直接自定义一个button,设置button的imageview属性实现,这样更加简单;

3.实现代码(采用第二种方法)

自定义一个UIbutton,如AnimateImgButton,实现方法

.m

//自定义button代码.m
- (id)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super initWithCoder:aDecoder]) {
        [self commonInit];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit{
    
}
- (CGRect)imageRectForContentRect:(CGRect)bounds{
  //重写 imageRectForContentRect 方法返回button的bounds,不然图片大小无法控制,btn.imageView setContentMode:UIViewContentModeScaleAspectFill]; 试过添加无效
    return CGRectMake(0.0, 0.0, self.size.width, self.size.height);
}
//重复动画
- (void)startImgAnimateWithImgArr:(NSArray *)imgArr time:(CGFloat)time
{
    [self.imageView setAnimationImages:imgArr];
    self.imageView.animationDuration = time;
    self.imageView.animationRepeatCount = 0;
    self.isPlayAnimate = YES;
    if (!self.imageView.isAnimating) {
        [self.imageView startAnimating];
    }
    
}
- (void)stopImgAnimate
{
    self.isPlayAnimate = NO;
    [self.imageView stopAnimating];
    self.imageView.animationImages = nil;
}

.h

/** 是否正在动画 */
@property (nonatomic, assign) BOOL isPlayAnimate;
//重复动画
- (void)startImgAnimateWithImgArr:(NSArray *)imgArr time:(CGFloat)time;
- (void)stopImgAnimate;

调用:

扫描二维码关注公众号,回复: 1026157 查看本文章
- (void)btnAnimateClick:(AnimateImgButton *)sender{
    if (sender.isPlayAnimate) {
        NSLog(@"关闭按钮动画");
        [sender stopImgAnimate];
    }else{
        NSLog(@"开启按钮动画");
        [self.btnAnimate startImgAnimateWithImgArr:self.imgArr time:1];
    }
}


- (AnimateImgButton *)btnAnimate{ if (!_btnAnimate) { _btnAnimate = [AnimateImgButton new]; _btnAnimate.isPlayAnimate = NO; [_btnAnimate setImage:kImage(@"IMGVoice3") forState:UIControlStateNormal]; [_btnAnimate addTarget:self action:@selector(btnAnimateClick:) forControlEvents:UIControlEventTouchUpInside]; } return _btnAnimate; } - (NSArray *)imgArr{ if (!_imgArr) { _imgArr = [NSArray arrayWithObjects: [UIImage imageNamed:@"IMGVoice1"], [UIImage imageNamed:@"IMGVoice2"], [UIImage imageNamed:@"IMGVoice3"],nil]; } return _imgArr; }

猜你喜欢

转载自www.cnblogs.com/wusang/p/9089107.html