为什么以下Core Animation隐式动画不起作用?

时间:2012-01-17 07:56:28

标签: ios core-animation

以下代码是CALayer的子类。如果我致电animateVal,则drawInContext会动画。那很棒。

我试图将其转换为actionForKey的隐式动画。如果我为val属性(layer.val = 10)分配了值,则会立即更改val,并使用相同的值drawInContext重复调用val,一个我刚刚分配的,一遍又一遍。

我做错了什么?

@interface MyLayer : CALayer
@property (nonatomic, assign) CGFloat val;
- (void)animateVal:(CGFloat)val;
@end

@implementation MyLayer
@dynamic val;

+ (BOOL)needsDisplayForKey:(NSString *)key {
    return [key isEqualToString:@"val"] || [super needsDisplayForKey:key];
}

- (id<CAAction>)actionForKey:(NSString *)event {
    if ([event isEqualToString:@"val"]) {
        CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"val"];
        anim.duration = 3.0;
        return anim;
    }

    return [super actionForKey:event];
}

- (void)animateVal:(CGFloat)val {
    CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"val"];
    anim.toValue = [NSNumber numberWithFloat:val];
    anim.duration = 3.0;
    [self addAnimation:anim forKey:nil];
}

- (void)drawInContext:(CGContextRef)ctx {

    CGContextAddRect(ctx, CGRectMake(10, 10, self.val, self.val));
    CGContextSetFillColorWithColor(ctx, [UIColor greenColor].CGColor);
    CGContextFillPath(ctx);
}

@end

1 个答案:

答案 0 :(得分:1)

哎呀。

解决方案是在返回操作时设置 fromValue

    anim.fromValue = [[self presentationLayer] valueForKey:event];