围绕中心旋转NSView

时间:2013-07-11 15:02:08

标签: objective-c macos cocoa nsanimation nsanimationcontext

我正在试图围绕其中心围绕NSView的旋转进行动画制作,但它在旋转过程中会一直左右移动。造成这种情况的原因是什么?

-(void)startRefreshAnimation {

    [NSAnimationContext beginGrouping];
    [[NSAnimationContext currentContext] setDuration:1.0];
    [[NSAnimationContext currentContext] setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
    [NSAnimationContext currentContext].completionHandler = ^{ [self startRefreshAnimation]; };
    [[view animator] setFrameCenterRotation:previousRotation - 90.0];
    previousRotation += -90.0;
    [NSAnimationContext endGrouping];

}

在轮换期间上移:

enter image description here

在轮换期间向下移动:

enter image description here

2 个答案:

答案 0 :(得分:1)

来自文档:

如果应用程序更改了图层的anchorPoint属性,则行为未定义。将此消息发送到未管理Core Animation层的视图会导致异常。

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSView_Class/Reference/NSView.html

您的视图是否使用未修改的定位点管理CALayer?

修改

我设置了类似的代码得到了完全相同的结果。不调整原点或锚点可以解决此问题。我的理论是这个特定的方法包含错误(用于自动布局),或者以我们没有预料到的方式工作。我使用CABasicAnimation获得了正确的效果。

/* setup */

....
     _view.layer.anchorPoint = CGPointMake(0.5f, 0.5f);
     _view.layer.position = ...

    [self startRefreshAnimation];
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    [self startRefreshAnimation];
}

-(void)startRefreshAnimation {

    CABasicAnimation *anim2 = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    anim2.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    anim2.fromValue = [NSNumber numberWithFloat:previousRotation * (M_PI / 180.0f)];
    anim2.toValue = [NSNumber numberWithFloat:(previousRotation + 90.0f) * (M_PI / 180.0f)];
    previousRotation = previousRotation + 90.0f;
    anim2.duration = 1.0f;
    anim2.delegate = self;
    [_view.layer addAnimation:anim forKey:@"transform"];
}

答案 1 :(得分:1)

这是虚拟项目和我找到的答案。 (适用于Cocoa Applicaiton)

Rotate NSImageView

github project (download)