ios - 在 CALayer 层次结构中组合多个 CAAnimation

标签 ios core-animation calayer

我有一段相当简单的示例代码,其中我有一个由三层组成的简单层次结构;

view layer
  |- base layer
    |- green layer

现在我想移动基础层并同时调整绿色层的颜色,所以我添加了一个 slider 来控制动画。

代码如下所示:

@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(这显然有效),或者我是否遗漏了一些东西,我可以做更多智能解决方案?

(当然这是一个简单的例子,但我的实际层次结构可能更复杂一些,理论上有任意层数)

最佳答案

当您从子层(在本例中为 greenLayer)中移除 speed = 0 时,它应该可以工作。

速度属性相对于父层起作用,因此您可以通过调整父层的速度来暂停所有动画。子层上的速度将相对于父层速度起作用。

关于ios - 在 CALayer 层次结构中组合多个 CAAnimation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28151210/

相关文章:

objective-c - 带有动画的ios简单条形图

objective-c - 在后台线程中下载多个文件

objective-c - 在 UIImageView 之上绘制使图像透明

ios - CATransform3D - 理解变换值

ios - Swift 从 UIView 层获取 UIImage

ios - 图片加载到 UIButton 时不会显示

ios - iPv6 支持可达性等级

ios - UILabel 动画淡入淡出不起作用

ios - 颜色问题外的惊人角半径