【问题标题】:Animate a CAShapeLayer's subclass custom property based on the path property基于路径属性为 CAShapeLayer 的子类自定义属性设置动画
【发布时间】:2014-05-09 18:21:25
【问题描述】:

我有一个 CAShapeLayer 子类,它具有两个属性,一个 startPoint 和一个 endPoint。这些属性不直接绘制到上下文中,而是用于改变路径属性,类似于变换、位置和边界属性。

这是整个层的代码

-(void)setStartPoint:(CGPoint)startPoint {
    if (!CGPointEqualToPoint(_startPoint, startPoint)) {
        _startPoint = startPoint;

        [self reloadPath];
    }
}

-(void)setEndPoint:(CGPoint)endPoint {
    if (!CGPointEqualToPoint(_endPoint, endPoint)) {
        _endPoint = endPoint;

        [self reloadPath];
    }
}

-(id)initWithLayer:(CRPathLayer*)layer {
    self = [super initWithLayer:layer];
    if (self && [layer isKindOfClass:[CRPathLayer class]]) {
        self.startPoint = layer.startPoint;
        self.endPoint = layer.endPoint;
    }

    return self;
}

+(BOOL)needsDisplayForKey:(NSString *)key {
    if ([key isEqualToString:NSStringFromSelector(@selector(startPoint))] || [key isEqualToString:NSStringFromSelector(@selector(endPoint))]) {
        return YES;
    }

    return [super needsDisplayForKey:key];
}

-(void)reloadPath {
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, self.startPoint.x, self.startPoint.y);
    CGPathAddLineToPoint(path, NULL, self.endPoint.x, self.endPoint.y);

    self.path = path;
    CGPathRelease(path);
}

但是有一个问题。我需要为两个新属性(起点或终点)之一设置动画。我知道我可以直接为 path 属性设置动画,但这不是我想要实现的。 我显然在实现中遗漏了一些东西。当我尝试使用 CABasicAnimation 对其进行动画处理时,什么也没有发生。

有人可以帮我吗? 提前致谢。

【问题讨论】:

    标签: ios cocoa-touch animation core-animation calayer


    【解决方案1】:

    您缺少的是 actionForKey: 方法(虽然 path 是可动画的,但它不是隐式可动画的(即它不会因为属性更改而动画)。

    您要做的是在 startPoint 或 endPoint 发生变化时为路径提供一个动作(动画的更通用术语)(或者只是使路径隐式动画化,以便设置新路径会导致动画,它们真的做同样的事情)。

    它可能看起来像这样(我在浏览器中输入了这个,所以它可能无法编译):

    - (id <CAAction>)actionForKey:(NSString *)key 
    {
        if ([key isEqualToString:@"startPoint"] || [key isEqualToString:@"endPoint")]) {
            CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"path"];
            anim.fromValue = [self.presentationLayer valueFoKey:@"path"];
            return animo;
        }
    
        return [super valueForKey:key];
    }
    

    【讨论】:

    • 嗯,原来 @"startPoint" 或 @"endPoint" 都没有调用 actionForKey
    • Core Animation 喜欢它的属性@dynamic。你做到了吗?
    • 好吧,我已经尝试过了,但是问题出现了,我应该何时重新计算路径。
    • 你可以坚持在actionForKey: 中检查@"path"
    • 好吧,我还需要设置计算路径而不使用动画。我现在所做的是观察起点和终点。如果它们发生变化,它将重新加载路径。问题是动画仍然不起作用。 actionForKey 被调用,但仅在初始化时调用。所以presentationLayer的路径还是nil。
    猜你喜欢
    • 1970-01-01
    • 2011-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-13
    • 1970-01-01
    • 2019-03-27
    相关资源
    最近更新 更多