核心动画:在10.8上设置anchorPoint以围绕其中心旋转图层

Bry*_*yan 10 macos cocoa core-animation core-graphics objective-c

注意:这适用于OS X上的Cocoa应用程序,而不是iOS.

我有一个支持图层的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];
Run Code Online (Sandbox Code Playgroud)

这是有效的,除了它运行时,图层向下跳到左边,使其中心点位于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.
Run Code Online (Sandbox Code Playgroud)

这意味着AppKit在上面的代码中"忽略"我对-setAnchorPoint的调用,而是将该锚点设置为NSView的原点(0,0).

我的问题是:我该如何解决这个问题?什么是"适当的NSView封面方法"来设置图层的anchorPoint(我在NSView上找不到这样的方法).在一天结束时,我只是希望我的按钮无限期地围绕其中心点旋转.

rob*_*off 16

我没有看到任何方法NSView是直接的"掩护" anchorPoint.

除了你引用的内容之外,我在10.8发行说明中看到是:

anchorPoint也始终设置为(0,0),...

anchorPoint层的控制点位于超层position的坐标系中. NSView设置self.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);
Run Code Online (Sandbox Code Playgroud)