-重点看暂停和恢复的操作
这个maskLayer 是你定义的属性(就是你哪个控件在做动画操作)
//开始动画
- (void)startShimmer {
dispatch_async(dispatch_get_main_queue(), ^{
// 切换到主线程串行队列,下面代码打包成一个事件(原子操作),加到runloop,就不用担心 isPlaying 被多个线程同时修改
// dispatch_async() 不 strong 持有本 block,也不用担心循环引用
if (self.isPlaying == true) return ;
self.isPlaying = true;
[self copyLabel:self.maskLabel from:self.contentLabel];
self.maskLabel.hidden = false;
[self.maskLayer removeFromSuperlayer];
[self freshMaskLayer];
[self.maskLabel.layer addSublayer:self.maskLayer];
self.maskLabel.layer.mask = self.maskLayer;
switch (self.shimmerType) {
case ST_LeftToRight: {
self.maskLayer.transform = self.startT;
self.translate.fromValue = [NSValue valueWithCATransform3D:self.startT];
self.translate.toValue = [NSValue valueWithCATransform3D:self.endT];
[self.maskLayer removeAllAnimations];
[self.maskLayer addAnimation:self.translate forKey:@"start"];
break;
}
case ST_RightToLeft: {
self.maskLayer.transform = self.endT;
self.translate.fromValue = [NSValue valueWithCATransform3D:self.endT];
self.translate.toValue = [NSValue valueWithCATransform3D:self.startT];
[self.maskLayer removeAllAnimations];
[self.maskLayer addAnimation:self.translate forKey:@"start"];
break;
}
case ST_AutoReverse : {
self.maskLayer.transform = self.startT;
self.translate.fromValue = [NSValue valueWithCATransform3D:self.startT];
self.translate.toValue = [NSValue valueWithCATransform3D:self.endT];
[self.maskLayer removeAllAnimations];
[self.maskLayer addAnimation:self.translate forKey:@"start"];
break;
}
case ST_ShimmerAll : {
self.maskLayer.transform = CATransform3DIdentity;
[self.maskLayer removeAllAnimations];
[self.maskLayer addAnimation:self.alphaAni forKey:@"start"];
break;
}
default: break;
}
});
}
//暂停动画
-(void)pauseLayer{
dispatch_async(dispatch_get_main_queue(), ^{
if (self.isPlaying == false) return ;
self.isPlaying = false;
CFTimeInterval pausedTime = [self.maskLayer convertTime:CACurrentMediaTime() fromLayer:nil];
self.maskLayer.speed = 0.0;
self.maskLayer.timeOffset = pausedTime;
});
}
//继续动画
-(void)resumeLayer{
CFTimeInterval pausedTime = [self.maskLayer timeOffset];
self.maskLayer.speed = 1.0;
self.maskLayer.timeOffset = 0.0;
self.maskLayer.beginTime = 0.0;
CFTimeInterval timeSincePause = [self.maskLayer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
self.maskLayer.beginTime = timeSincePause;
}
//结束动画
- (void)stopShimmer {
dispatch_async(dispatch_get_main_queue(), ^{
if (self.isPlaying == false) return ;
self.isPlaying = false;
[self.maskLayer removeAllAnimations];
[self.maskLayer removeFromSuperlayer];
self.maskLabel.hidden = true;
});
}
感谢关注作者!