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

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

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"]; 

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

我从来没有试过这样做,但你应该能够(可能通过KVO?)在动画过程中监视CALayer的frame属性(或positionboundsanchorPoint ,具体取决于你需要的)。

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

例如,

 CGPoint currentPosition = [[moveLayer presentationLayer] position]; 

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

如果您的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正在旋转并且位置正在改变,我想得到一个子CALayer的位置相对于父级所属的UIView中的触摸位置。 所以这是基本的想法,但我实际上并没有运行这个伪代码版本。