您的位置:首页 > 其它

Core Animation实例1-音量振动条(CAReplicatorLayer复制层)

2016-02-03 10:11 288 查看


分析震动条界面

每一个条都在做一个上下缩放的动画.而且不需要与用户交互.所以每一个震动条可以用CALayer来做.

发现每个都非常相似.所以先搞定一个,然后其它的直接复制就可以了.

添加动画

添加高度缩小后,马上还原

为什么选用核心动画?

给图层做动画用核心动画,不需要与用户做交互.

采用哪一种核心动画?

把它的缩放改成某个值就好了.选用CABasicAnimation

CABasicAnimation *anim = [CABasicAnimation animation];

动画时长

anim.duration = 2;

形变缩放动画

anim.keyPath = @”transform.scale”;

改为0,让它缩小

anim.toValue = @0;

让动画一直执行

anim.repeatCount = MAXFLOAT;

反转回去

anim.autoreverses = YES;

[layer addAnimation:anim forKey:nil];

运行发现:不是我们想要的上下进行缩放?它是绕着中心点去缩放?

所以要设置锚点. 设置锚点就不能设置frame了, 要设置Position

设置锚点

layer.anchorPoint = CGPointMake(0, 1);

设置position

layer.position = CGPointMake(0, _contentsView.bounds.size.height);

不能够再用frame,设置它的bounds

layer.bounds = CGRectMake(0, 0, barW, barW);

运行发现:是不是 x轴 和 Y轴一起缩放了

不需要X轴缩放,所以更改动画的KeyPath

anim.keyPath = @”transfrom.scale.y”

使用复制层

复制层可以把它里面的所有子层给复制.

添加复制层,首先先要让这个层显示出来.

复制层必须加到一个层里面才能复制它的子层.

不需要设置它的尺寸, 需要设置它的颜色.子层超过父层也能够显示,所以不用设置尺寸.

CAReplicatorLayer *replicator = [CAReplicatorLayer  layer];
将复制层添加到_contententView.layer
[_contentsView.layer addSublayer:replicator];

instanceCount:表示原来层中的所有子层复制的份数
replicator.instanceCount = 2;

在复制层中添加子层
[replicator addSublayer:layer];

运行发现没有两个,为什么?
其实已经有两个了,两个的位置,尺寸都是一样的,所以看着只有一个.

解决办法:让子层有偏移位置
instanceTransform:复制出来的层,相对上一个子层的形变
replicator.instanceTransform = CATransform3DMakeTranslation(45, 0, 0);

现在复制出来的层,执行的动画,都一样, 怎么样才能有错乱的感觉?

相对于上一个层的动画延时
replicator.instanceDelay = 0.3;

使用它,应该把原始层的颜色设置为白色
replicator.instanceColor = [UIColor greenColor].CGColor;


[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

// 复制层:复制里面的子层
CAReplicatorLayer *repL = [CAReplicatorLayer layer];
repL.frame = _contentView.bounds;

// instanceCount:表示复制层中有多少份子层,拷贝是instanceCount - 1份
repL.instanceCount = 4;

// 设置复制子层偏移量,每个子层都会相对上一次偏移
repL.instanceTransform = CATransform3DMakeTranslation(40, 0, 0);

// 延迟每个子层的动画,相对于上一个子层延迟
repL.instanceDelay = 0.2;

// 设置子层的颜色
repL.instanceColor = [UIColor colorWithWhite:1 alpha:0.2].CGColor;

[_contentView.layer addSublayer:repL];

// 红色的图层
CALayer *layer = [CALayer layer];

layer.backgroundColor = [UIColor redColor].CGColor;

//    layer.frame = CGRectMake(0, 100, 30, 100);

layer.anchorPoint = CGPointMake(0, 1);
layer.position = CGPointMake(0, 200);
layer.bounds = CGRectMake(0, 0, 30, 100);

// 把红色图层添加到复制层中
[repL addSublayer:layer];

CABasicAnimation *anim = [CABasicAnimation animation];

anim.keyPath = @"transform.scale.y";

anim.toValue = @0;

anim.duration = 0.5;

// 设置动画反转
anim.autoreverses = YES;

anim.repeatCount = MAXFLOAT;

[layer addAnimation:anim forKey:nil];

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