我有这个相当简单的示例代码,其中我有一个由三层组成的简单层次结构;
view layer
|- base layer
|- green layer
现在我想移动基础层,同时调整绿色层的颜色,所以我添加了一个滑块来控制动画。
代码如下所示:
@implementation ViewController
- (void)loadView
{
[super loadView];
baseLayer = [CALayer layer];
[baseLayer setFrame:[[self view] frame]];
[baseLayer setBackgroundColor:[[[UIColor redColor] colorWithAlphaComponent:0.5] CGColor]];
[[[self view] layer] addSublayer:baseLayer];
greenLayer = [CALayer layer];
[greenLayer setBounds:[baseLayer bounds]];
[greenLayer setBackgroundColor:[[UIColor greenColor] CGColor]];
[baseLayer addSublayer:greenLayer];
UISlider *slider = [[UISlider alloc] initWithFrame:CGRectMake(0, CGRectGetHeight([[self view] bounds]) - 44.0f, CGRectGetWidth([[self view] bounds]), 44.0f)];
[slider addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
[[self view] addSubview:slider];
CABasicAnimation *changeColor = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];
changeColor.fromValue = (id)[UIColor greenColor].CGColor;
changeColor.toValue = (id)[UIColor blueColor].CGColor;
changeColor.duration = 1.0; // For convenience
[greenLayer addAnimation:changeColor forKey:@"Change color"];
greenLayer.speed = 0.0; // Pause the animation
CABasicAnimation *changePosition = [CABasicAnimation animationWithKeyPath:@"position"];
changePosition.fromValue = [NSValue valueWithCGPoint:CGPointMake(CGRectGetWidth([[self view] bounds]) / 2, CGRectGetHeight([[self view] bounds]) / 2)];
changePosition.toValue = [NSValue valueWithCGPoint:CGPointMake(CGRectGetWidth([[self view] bounds]), CGRectGetHeight([[self view] bounds]) / 2)];
changePosition.duration = 1.0;
[baseLayer addAnimation:changePosition forKey:@"Change position"];
baseLayer.speed = 0.0;
}
- (void)sliderValueChanged:(UISlider *)slider
{
[baseLayer setTimeOffset:[slider value]];
[greenLayer setTimeOffset:[slider value]];
}
我的问题:我是否需要逐个更改每个图层的timeOffset
(这显然有效),或者我在这里遗漏了一些内容,我可以使用更智能的解决方案吗?
(当然这是一个简单的例子,但我的实际层次结构可能有点复杂,理论上有任意数量的层次)
答案 0 :(得分:2)
当您从子图层中移除速度= 0时,它应该有效,在本例中为greenLayer。
speed属性相对于父图层有效,因此您可以通过调整父图层的速度来暂停所有动画。子层的速度将相对于父层速度起作用。