2013-02-12 165 views
8

注意:这是针对OS X上的Cocoa应用程序,而不是iOS。核心动画:在10.8上设置anchorPoint以围绕其中心旋转一层

我有一个层支持NSButton(NSView的子类)。我想要做的是使用Core Animation旋转该按钮。我使用下面的代码来做到这一点:

CABasicAnimation *a = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"]; 
a.fromValue = [NSNumber numberWithFloat:0]; 
a.toValue = [NSNumber numberWithFloat:-M_PI*2]; 
[_refreshButton.layer setAnchorPoint:CGPointMake(0.5, 0.5)]; 
a.duration = 1.8; // seconds 
a.repeatCount = HUGE_VAL; 
[_refreshButton.layer addAnimation:a forKey:nil]; 

这工作,但它运行时,层跳下,并向左以便其中心点是在一个NSView,起源点,这(0,0)的左下角。然后该层围绕其中心旋转,但显然跳到较低的左角是不可接受的。

所以,大量的阅读之后,我发现这条线在10.8 API的版本说明:

On 10.8, AppKit will control the following properties on a CALayer 
(both when "layer-hosted" or "layer-backed"): geometryFlipped, bounds, 
frame (implied), position, anchorPoint, transform, shadow*, hidden, 
filters, and compositingFilter. Use the appropriate NSView cover methods 
to change these properties. 

这意味着,AppKit的被“忽略”我呼吁在上面的代码-setAnchorPoint,取而代之的,是将该锚点设置为NSView的原点(0,0)。

我的问题是:我该如何解决这个问题?什么是“合适的NSView覆盖方法”来设置图层的anchorPoint(我无法在NSView上找到这样的方法)。在一天结束时,我只想让我的按钮无限期地围绕其中心点旋转。

回答

15

我没有看到NSView上的任何方法,它们是anchorPoint的直接“覆盖”。

我看到the 10.8 release notes什么,除了你报的是什么,是这样的:

的anchorPoint也一直被设置为(0,0),...

anchorPoint控制哪些在超层坐标系中,该层的点位于positionNSViewself.layer.anchorPoint设置为(0,0),表示该图层的左下角位于self.layer.position

当您将anchorPoint设置为(0.5,0.5)时,表示图层的中心应位于图层的position处。由于您没有修改position,因此您会看到这会将图层向下移动到左侧。

你需要计算position你想要的层具有当其anchorPoint为(0.5,0.5),像这样:

CGRect frame = _refreshButton.layer.frame; 
CGPoint center = CGPointMake(CGRectGetMidX(frame), CGRectGetMidY(frame)); 
_refreshButton.layer.position = center; 
_refreshButton.layer.anchorPoint = CGPointMake(0.5, 0.5); 
+0

完美!你懂;我看到了位置属性,但没有尝试,因为我读了上面的说明,说AppKit将控制它。感谢您的解决方案! – Bryan 2013-02-13 01:15:26

+0

任何想法为什么旋转M_PI/2会第一次逆时针旋转,然后顺时针旋转? – greg 2014-07-08 04:23:30

+0

我将不得不看你的代码。你应该发布你自己的问题。 – 2014-07-08 05:36:05