Animate之前添加了CALayer动画

时间:2013-12-03 00:24:22

标签: ios core-animation quartz-core

我正在处理一个组件,该组件应该渲染多个图像并在更改内容时设置其位置。我受到了这篇文章的启发:http://ronnqvi.st/controlling-animation-timing/并想到使用速度来控制动画。

我的想法是将带有动画的CALayers添加到速度为0的顶级图层,然后在设置动画时将此图层的速度设置为1.0。

以下是代码:

...

@property (nonatomic,strong) CALayer *animationLayer;

...

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) 
    {
         self.animationLayer = [CALayer layer];
         self.animationLayer.frame = frame;
         self.animationLayer.speed = 0.0;
         [self.layer addSublayer:self.animationLayer];
    }
    return self;
}

- (void)addLayerData:(LayerData*)layerData
{
    CALayer *aLayer = [CALayer layer];
    aLayer.contents = (id) layerData.image.CGImage;
    aLayer.frame = CGRectMake(0,0,96,96);
    aLayer.position = layerData.position;
    aLayer.name = layerData.name;

    CGRect pathLayerFrame = layerData.path.bounds;
    pathLayerFrame.origin.x = 0.0;
    pathLayerFrame.origin.y = 0.0;

    CAShapeLayer *pathLayer = [CAShapeLayer layer];
    pathLayer.frame = pathLayerFrame;
    pathLayer.path = layerData.path.CGPath;
    pathLayer.strokeColor = layerData.strokeColor.CGColor;
    pathLayer.fillColor = [UIColor clearColor].CGColor;
    pathLayer.lineWidth = 10;
    pathLayer.lineCap = kCALineCapRound;

    [self.animationLayer addSublayer:pathLayer];

    CAKeyframeAnimation *positionAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    [positionAnimation setPath: layerData.path.CGPath];
    [positionAnimation setDuration: 10.0];
    [positionAnimation setRemovedOnCompletion: NO];
    [positionAnimation setFillMode: kCAFillModeBoth];
    [positionAnimation setKeyTimes:layerData.keyTimes];

    CAKeyframeAnimation *contentsAnimation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];
    [contentsAnimation setValues:[self buildContentImagesFromLayerData:layerData];
    [contentsAnimation setCalculationMode:kCAAnimationDiscrete];
    contentsAnimation.calculationMode = kCAAnimationLinear;
    [contentsAnimation setDuration:0.1];
    [contentsAnimation setDelegate:self];
    [contentsAnimation setAutoreverses:YES];
    [contentsAnimation setRepeatCount:HUGE_VALF];
    [contentsAnimation setRemovedOnCompletion:NO];
    [contentsAnimation setFillMode:kCAFillModeBoth];

    [aLayer addAnimation:positionAnimation forKey:kPostionAnimationKey];
    [aLayer addAnimation:contentsAnimation forKey:kContentsAnimationKey];

    [self.animationLayer addSublayer:aLayer];
}

- (void)animate
{
     self.animationLayer.speed = 1.0;
}

我的问题是虽然animationLayer包含了所有要设置动画的图层,并且这些图层的所有动画都已正确定义,但我似乎无法让图层在屏幕上移动。

在不同时间(即用户点击按钮添加图像时),外部客户端代码会多次调用addLayerData。当用户点击按钮时,将调用animate。

也许我错过了文章中的内容。

任何人都可以帮我解决这个问题吗?

提前致谢。

更新

如果我删除animationLayer并直接在视图的图层(self.layer)上添加要动画的图层,它就可以正常工作。

0 个答案:

没有答案