簡體   English   中英

如何在動畫過程中找到CAlayer的位置?

[英]how find position of CAlayer during animation?

我正在實現游戲應用程序,其中我正在使用動畫圖層。

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

現在我想在動畫過程中找到圖層的位置?是可能的嗎?請幫幫我。

為了在動畫過程中找到當前位置,您將需要查看圖層的presentationLayer的屬性。 圖層本身的屬性將僅反映隱式動畫的最終目標值,或應用CABasicAnimation之前的初始值。 presentationLayer為您提供動畫的任何屬性的瞬時值。

例如,

CGPoint currentPosition = [[moveLayer presentationLayer] position];

會在顯示動畫路徑時為您提供該圖層的當前位置。 不幸的是,我認為很難在表示層中使用鍵值觀察,因此,如果要跟蹤它,可能需要手動輪詢該值。

我從未嘗試過這樣做,但是您應該能夠在動畫過程中(也許通過KVO嗎?)監視CALayer的frame屬性(或positionboundsanchorPoint ,具體取決於您的需求)。

如果您的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中的觸摸位置的位置。 所以這是基本思想,但我實際上沒有運行此偽代碼版本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM