CAAnimation 在一个点上进行变换旋转

Posted

技术标签:

【中文标题】CAAnimation 在一个点上进行变换旋转【英文标题】:CAAnimation with an transform rotation over an point 【发布时间】:2014-03-07 20:44:45 【问题描述】:

我正在尝试为视图层在任意点上的旋转设置动画。动画的开始位置将是从结束位置到最终位置的90º 旋转。此视图占据除状态栏外的所有屏幕。

我正在尝试使用以下代码(带有平移,然后是旋转和反平移),但是,无论在其中开始和结束,动画都不是以该点为中心,而是围绕它摆动。

CABasicAnimation *animation = [CABasicAnimation   animationWithKeyPath:@"transform"];
animation.duration = 1;
animation.additive = YES;
animation.removedOnCompletion = YES;
animation.fillMode = kCAFillModeRemoved;

//The point that should be used as the center of rotation
CGPoint cursorCenter=self.angleCenter;
//The center of the view
CGPoint linesCenter=lines.center;

//The transformation: translate->rotate->anti-translate
CATransform3D transform = CATransform3DIdentity;
transform = CATransform3DTranslate(transform, cursorCenter.x-linesCenter.x, cursorCenter.y-linesCenter.y, 0.0);
transform = CATransform3DRotate(transform, degreesToRadians(-90), 0.0, 0.0, -1.0);
transform = CATransform3DTranslate(transform, linesCenter.x-cursorCenter.x, linesCenter.y-cursorCenter.y, 0.0);

animation.fromValue =[NSValue valueWithCATransform3D:transform];
animation.toValue =[NSValue valueWithCATransform3D:CATransform3DIdentity];    

[lines.layer addAnimation:animation forKey:@"90rotation"];

我做错了什么?

【问题讨论】:

不久前我写了一个blog post called "translate rotate translate?" 来讨论这种动画。这可能值得一读。 我已经读过了。问题是我正在使用自动布局。堆栈溢出链接上的解决方案谈到了层变换,但我已经在使用它了。 【参考方案1】:

您无需进行平移即可在特定点上旋转。只需更改图层的anchorPoint调整旋转中心

变换的原点是 center 属性的值,或者 图层的 anchorPoint 属性(如果已更改)。

关于锚点以及如何指定:

您使用单位坐标指定此属性的值 空间。该属性的默认值为 (0.5, 0.5),即 表示图层边界矩形的中心。全几何 对视图的操作发生在指定点附近。为了 例如,将旋转变换应用于具有默认值的图层 锚点使图层围绕其中心旋转。 变化 锚点到不同的位置会导致图层 围绕该新点旋转。

基于CALayer Class Reference 和Core Animation Programming Guide

【讨论】:

以上是关于CAAnimation 在一个点上进行变换旋转的主要内容,如果未能解决你的问题,请参考以下文章

闫令琪GAMES101笔记 变换

有没有办法用关键点进行 3D 变换?

CAAnimation 层取消视图的 previos 变换

在变换中缩放和旋转矩阵?

5、求绕平面上任意点旋转的变换矩阵。

Swift 2:仅在全屏视频上进行屏幕旋转