如何在动画中找到CAlayer的位置?

时间:2009-12-19 05:05:45

标签: iphone ios

我正在实现游戏应用程序。我在其中使用动画层。

CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, previousValuex, previousValue);
CGPathAddLineToPoint(path, NULL, valuex, value);
previousValue=value;
previousValuex=valuex;

CAKeyframeAnimation *animation;
animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
animation.path = path;
animation.duration =1.0;
animation.repeatCount = 0;
//animation.rotationMode = kCAAnimationRotateAutoReverse;
animation.calculationMode = kCAAnimationPaced;

// Create a new layer for the animation to run in.
CALayer *moveLayer = [imgObject layer];
[moveLayer addAnimation:animation forKey:@"position"];

现在我想在动画中找到图层位置?可以吗?请帮助我。

3 个答案:

答案 0 :(得分:24)

为了在动画中找到当前位置,您需要查看图层presentationLayer的属性。图层本身的属性仅反映隐式动画的最终目标值,或者应用CABasicAnimation之前的初始值。 presentationLayer为您提供动画属性的瞬时值。

例如,

CGPoint currentPosition = [[moveLayer presentationLayer] position];

将为您提供图层的当前位置,因为它会为您的路径制作动画。不幸的是,我认为很难对表示层使用键值观察,因此如果要跟踪它,可能需要手动轮询该值。

答案 1 :(得分:0)

我从未尝试过这样做,但您应该能够(可能通过KVO?)监控CALayer的frame属性(或positionbounds或{ {1}},取决于您需要的动画。

答案 2 :(得分:0)

如果您的CALayer在另一个CALayer中,您可能需要应用父CALayer的affineTransform来获取子CALayer的位置,如下所示:

// Create your layers
CALayer *child = CALayer.layer;
CALayer *parent = self.view.layer;
[parent addSubLayer:child];

// Apply animations, transforms etc...

// Child center relative to parent
CGPoint childPosition = ((CALayer *)child.presentationLayer).position;

// Parent center relative to UIView
CGPoint parentPosition = ((CALayer *)parent.presentationLayer).position;
CGPoint parentCenter = CGPointMake(parent.bounds.size.width/2.0, parent.bounds.size.height /2.0);

// Child center relative to parent center
CGPoint relativePos = CGPointMake(childPosition.x - parentCenter.x, childPosition.y - parentCenter.y);

// Transformed child position based on parent's transform (rotations, scale etc)
CGPoint transformedChildPos = CGPointApplyAffineTransform(relativePos, ((CALayer *)parent.presentationLayer).affineTransform);

// And finally...
CGPoint positionInView = CGPointMake(parentPosition.x +transformedChildPos.x, parentPosition.y + transformedChildPos.y);

此代码基于我刚刚编写的代码,其中父CALayer正在旋转并且位置正在改变,我想获得相对于父母所属的UIView中的触摸位置的子CALayer的位置。所以这是基本的想法,但我实际上并没有运行这个伪代码版本。