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;

調用:

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM