NSImageView 希望从尝试旋转时的位置开始。如何阻止它?

NSImageView is hoping when from the location when trying to rotate. How to stop it?

我正在从它的中心旋转一个 NSImageView,它工作得很好,但是当我开始动画时,NSImageView 从它的位置跳到一个随机位置。我不知道为什么会这样。请帮忙

我正在详细说明我是如何做的。另外,我提供了 Github link 以便您可以 运行 如果需要。

github project link

代码:

// on button press animation will be started
-(void)buttonPressed:(id)sender{

    // setting the anchor point of the view
    _img.layer.anchorPoint = CGPointMake(0.5f, 0.5f);

    // calling the animation function
    [self startRefreshAnimation];
}

// in order to repeate the animation
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    [self startRefreshAnimation];
}

// the function that will handel all the animation stuff
-(void)startRefreshAnimation {

    CABasicAnimation *anim2 = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    anim2.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];

    NSNumber* toValue = [NSNumber numberWithFloat:0 * (M_PI / 180.0f)];
    NSNumber* fromValue = [NSNumber numberWithFloat:(360.0f) * (M_PI / 180.0f)];


    anim2.fromValue = toValue;
    anim2.toValue = fromValue;


    anim2.duration = 1.0f;
    anim2.delegate = self;
    [_img.layer addAnimation:anim2 forKey:@"transform"];
}

对于您需要的动画任务,我认为代码很好。只需移动 anchorPoint 线,如下所示:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // Insert code here to initialize your application

    _img.layer.anchorPoint = CGPointMake(0.5f, 0.5f);   
}

编辑: 基本上,图层的位置是根据图层锚点的位置指定的。当您设置图层的位置时,您就是在其超图层的坐标系中设置图层中心的位置。因为位置是相对于图层的锚点,所以在保持相同位置的同时更改该锚点会移动图层。因此,您必须在渲染子视图之前设置锚点。


此外,对于无限重复,您可以避免编写 animationDidStop 方法,方法是使用此 属性:

anim2.repeatCount = HUGE_VALF;

您需要在图像视图上设置图层的位置。在 buttonPressed 方法中添加:

//Position of the imgView
CGRect frame = _img.layer.frame;

float xCoord = frame.origin.x + frame.size.width;
float yCoord = frame.origin.y + frame.size.height;

CGPoint myPoint = CGPointMake(xCoord, yCoord);
_img.layer.position = myPoint;

[self startRefreshAnimation]

那样的话,您可以在 .xib 中四处移动 imageView,动画就会出现在正确的位置。

编辑:@Nishant 的解决方案非常漂亮..

设置图层的锚点,使其围绕正确的中心旋转,然后立即重新定位以适应新的锚点(否则它会改变其位置):

    let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
    rotateAnimation.toValue = CGFloat(-M_PI * 2.0)
    rotateAnimation.duration = 1.0

    viewToRotate.layer?.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    viewToRotate.layer?.position = viewToRotate.center

    viewToRotate.layer?.addAnimation(rotateAnimation, forKey: nil)

与...

extension NSView {
var center: CGPoint {
    get {
        return CGPointMake(NSMidX(self.frame), NSMidY(self.frame))
    }
}