iOS UIButton设置图片动画

本文介绍了一种通过自定义UIButton实现控制动画播放与停止的方法,并结合音频播放功能。主要通过设置imageView动画图像数组和控制动画播放时长来实现动画效果。

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;

调用:

- (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; }

 

转载于:https://www.cnblogs.com/wusang/p/9089107.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值