下面这份代码是抄自”高仿酷狗音乐歌词“
// Created by liuyang on 16/3/14.
// Copyright © 2016年 ly. All rights reserved.
- (void)startLyricsAnimationWithTimeArray:(NSArray *)timeArray andLocationArray:(NSArray *)locationArray {
//每行歌词的时间总长
CGFloat totalDuration = [timeArray.lastObject floatValue]*1.0/1000;
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"bounds.size.width"];
NSMutableArray *keyTimeArray = [NSMutableArray array];
NSMutableArray *widthArray = [NSMutableArray array];
for (int i = 0 ; i < timeArray.count; i++) {
CGFloat tempTime = [timeArray[i] floatValue] *1.0/1000/totalDuration;
[keyTimeArray addObject:@(tempTime)];
CGFloat tempWidth = [locationArray[i] floatValue] * CGRectGetWidth(self.maskLable.frame);
[widthArray addObject:@(tempWidth)];
}
animation.values = widthArray;
animation.keyTimes = keyTimeArray;
animation.duration = totalDuration;
animation.calculationMode = kCAAnimationLinear;
animation.fillMode = kCAFillModeForwards;
animation.removedOnCompletion = NO;
[self.maskLayer addAnimation:animation forKey:@"MaskAnimation"];
}
- (void)stopAnimation {
//[self pauseLayer:self.maskLayer];
[self.maskLayer removeAllAnimations];
self.maskLayer=nil;
}
//暂停
-(void)pauseLayer:(CALayer*)layer
{
CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
// 让CALayer的时间停止走动
layer.speed = 0.0;
// 让CALayer的时间停留在pausedTime这个时刻
layer.timeOffset = pausedTime;
}
- (void)reAnimation
{
[self resumeLayer:self.maskLayer];
}
//恢复
-(void)resumeLayer:(CALayer*)layer
{
CFTimeInterval pausedTime = layer.timeOffset;
// 1. 让CALayer的时间继续行走
layer.speed = 1.0;
// 2. 取消上次记录的停留时刻
layer.timeOffset = 0.0;
// 3. 取消上次设置的时间
layer.beginTime = 0.0;
// 4. 计算暂停的时间(这里也可以用CACurrentMediaTime()-pausedTime)
CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
// 5. 设置相对于父坐标系的开始时间(往后退timeSincePause)
layer.beginTime = timeSincePause;
}
解释:
一.底部一个label,上面一个label,两个label 字体颜色不一样,但必须重合。
用时间去控制上面的label的显示,即可。
代码中,用了一个masklayer,通过改变width,控制显示的宽度。
网友评论