【问题标题】:Why is implicit animation missing when I add a sublayer to a layer?当我将子图层添加到图层时,为什么会丢失隐式动画?
【发布时间】:2013-03-19 19:54:10
【问题描述】:

在 UIView 子类中,我有这个方法:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch * aTouch = [touches anyObject];
    CGPoint loc = [aTouch locationInView:self];

    CALayer * layer = [CALayer layer];
    [layer setBackgroundColor: [[UIColor colorWithHue:(float)rand()/RAND_MAX saturation:1 brightness:1 alpha:1] CGColor]];
    [layer setFrame:CGRectMake(0, 0, 64, 64)];
    [layer setCornerRadius:7];
    [layer setPosition:loc];

    [layer setOpacity:0];

    [self.layer addSublayer:layer];


    CABasicAnimation * opacityAnim = [CABasicAnimation animationWithKeyPath:@"opacity"];
    opacityAnim.duration=2.42;
    opacityAnim.fromValue=[NSNumber numberWithFloat:0];
    opacityAnim.toValue=  [NSNumber numberWithFloat:1];
    opacityAnim.fillMode = kCAFillModeForwards;
    opacityAnim.timingFunction= [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    opacityAnim.removedOnCompletion=NO;
    opacityAnim.delegate=self;

//  explicit animation is working as expected
//  [layer addAnimation:opacityAnim forKey:@"opacityAnimation"];

//     Why isn't the implicit animation working ?
[layer setOpacity:1];
}

我错过了什么?我希望 CALayer layer 的不透明度使用此方法的最后一行进行隐式动画处理。

我的解决方案

感谢邓肯的回答,这是我解决问题的方法。

-(CALayer *) layerFactory:(CGPoint) loc {
    CALayer * layer = [CALayer layer];
    [layer setBackgroundColor: [[UIColor colorWithHue:(float)rand()/RAND_MAX saturation:1 brightness:1 alpha:1] CGColor]];
    [layer setFrame:CGRectMake(0, 0, 64, 64)];
    [layer setCornerRadius:7];
    [layer setPosition:loc];
    [layer setOpacity:0];
    return layer;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch * aTouch = [touches anyObject];
    CGPoint loc = [aTouch locationInView:self];


    [CATransaction begin];
    CALayer * layer = [self layerFactory:loc];
    [self.layer addSublayer:layer];
    [CATransaction commit];


    [CATransaction begin];
    [CATransaction setAnimationDuration:0.45];
    [layer setOpacity:1];
    [CATransaction commit];

}

您只需要将图层的创建和不透明度的修改放在两个不同的 CATransaction 块中。但是,将层的创建(而不是添加)移动到 layerFactory 方法并不会改变这种情况。

我不知道这是否是最好的解决方案,但它确实有效。

【问题讨论】:

标签: ios core-animation


【解决方案1】:

您不能创建一个图层并设置它的不透明度,然后以相同的方法将不透明度设置为一个新值并获得隐式动画。尝试将您的创建/配置层代码放在 CATransaction 开始/结束块中,然后将不透明度设置为 1 的代码放在另一个事务开始/结束块中。

我认为这会奏效,但必须尝试一下才能确定。

如果这不起作用,请调用代码以使用 performSelector:withObject:afterDelay 和延迟值 0 将不透明度设置为 1。这将使系统添加不透明度为 0 的图层,然后处理更改不透明度为 1 作为单独的事务。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-27
    • 1970-01-01
    • 2012-08-12
    • 1970-01-01
    • 2012-05-15
    • 1970-01-01
    • 2020-11-26
    • 1970-01-01
    相关资源
    最近更新 更多