注意:这是用于OS X而非iOS上的Cocoa应用程序。

我有一个层支持的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)的左下角。然后,该层绕其中心旋转,但是显然跳到左下角是 Not Acceptable 。

因此,经过大量阅读,我在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的调用,而是将 anchor 设置为NSView的原点(0,0)。

我的问题是:我该如何解决?什么是设置图层的anchorPoint的“适当的NSView覆盖方法”(我在NSView上找不到这样的方法)。最后,我只希望按钮无限期绕其中心点旋转。

最佳答案

我没有在NSView上看到任何直接作为anchorPoint的“封面”的方法。

除了您引用的内容,我在the 10.8 release notes中看到的是:


anchorPoint控制图层的哪个点在超层坐标系中的position处。 NSViewself.layer.anchorPoint设置为(0,0),这意味着该图层的左下角位于self.layer.position

anchorPoint设置为(0.5,0.5)时,这意味着层的中心应位于层的position处。如您所见,由于您没有修改position,因此具有将图层向下和向左移动的效果。

您需要计算当图层的position为(0.5,0.5)时希望图层具有的anchorPoint,如下所示:

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

关于objective-c - 核心动画: set anchorPoint on 10. 8围绕其中心旋转图层,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14839335/

10-09 16:13