您的位置:首页 > 移动开发 > IOS开发

iOS歌词渐变的实现

2016-05-13 15:19 357 查看
测试通过UIView动画动态改变UILabel的frame可以实现。

此次使用渲染的方式:

(1)建立两层Label,除文字颜色外其他属性同。

// 底层白色歌词
_behindLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 100, WIDTH - 20, 60)];
_behindLabel.text = @"你必须竭尽全力,才能看起来毫不费力。";
_behindLabel.font = [UIFont systemFontOfSize:18.0];
_behindLabel.backgroundColor = [UIColor clearColor];
_behindLabel.textColor = [UIColor whiteColor];
_behindLabel.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:_behindLabel];

// 上层绿色歌词
_frontLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 100, WIDTH - 20, 60)];
_frontLabel.text = @"你必须竭尽全力,才能看起来毫不费力。";
_frontLabel.font = [UIFont systemFontOfSize:18.0];
_frontLabel.backgroundColor = [UIColor clearColor];
_frontLabel.textColor = [UIColor orangeColor];
_frontLabel.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:_frontLabel];


(2)设置layer属性。

// 设置渲染
_layer = [CALayer layer];
// 设置渐变方向,默认情况下只渲染1/2,若y为1,则水平渲染1/2
_layer.anchorPoint = CGPointMake(0, 0.5);
// 30为Label高度的1/2
_layer.position = CGPointMake(0, 30);
// 初始值,高度为Label高度,其他均为零
_layer.bounds = CGRectMake(0, 0, 0, 60);
_layer.backgroundColor = [UIColor whiteColor].CGColor;

// 此处要同时渲染歌词Label和其SubView,单纯Label无动画效果,单纯sub无上曾文字显示也无效果
_frontLabel.layer.mask = _layer;
self.layer = _layer;


(3)设置关键帧动画,渲染法实现歌词渐变关键。

// 添加关键帧动画
// 此处的KeyPath 必须为bounds.size.width 否则无效果
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"bounds.size.width"];
animation.values = @[@(0),@(355)];
animation.keyTimes = @[@(0),@(1)];
animation.duration = 3.5;
animation.calculationMode = kCAAnimationLinear;
animation.fillMode = kCAFillModeForwards;
animation.removedOnCompletion = NO;
// 此处关键帧需要添加在sub上
[self.layer addAnimation:animation forKey:@"Animation"];


(4)接下来尝试歌词Lrc文件的解析,放在下期。

(5)最终完成效果如图示。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: