2009-12-19 40 views
1

我正在实现游戏应用程序。我在其中使用动画层。如何在动画期间找到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"]; 

现在我想在动画过程中找到图层的位置吗?是否可能?请帮助我。

回答

0

我从来没有尝试这样做,但你应该能够(可能通过志愿?)监测的CALayer的frame财产(或position,或者bounds,或anchorPoint,这取决于你的需要)在动画过程中。

+1

实际上,在这种情况下这不起作用。虽然您可以观察图层的属性,但它们只反映图层的开始或结束值,而不是其中的任何值。正如我在我的回答中所阐明的那样,在动画时,您需要查看presentationLayer获取图层的当前值。 – 2009-12-19 18:34:22

+0

啊,我明白了(正如我指出的,我从来没有尝试过我的建议!)。对于它的价值,我已经投票选出了你的答案。如果我需要在将来做类似的事情,很高兴知道。 – 2009-12-20 04:12:40

24

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

例如,

CGPoint currentPosition = [[moveLayer presentationLayer] position]; 

将让你的层的当前位置,因为它是关于动画的路径。不幸的是,我认为在表示层中使用键值观测很困难,所以如果你想跟踪它,你可能需要手动轮询这个值。

+0

您是否知道如何获得presentationLayer的** scale **? '[[presentationLayer valueForKeyPath:@“transform.scale”] floatValue]'返回最终值(而不是当前值)。 – aleclarson 2014-03-30 08:08:04

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正在旋转并且位置正在改变,并且我想要获得儿童CALayer相对于父母所属UIView中的触摸位置的位置。所以这是基本的想法,但我没有真正运行这个伪代码版本。