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

自古美人都是妖i 提交于 2019-12-02 10:13:05

The code looks fine to me for the animation task u require. Just move the anchorPoint line, like this:

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

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

EDIT: Basically, the position of a layer is specified in terms of the location of the layer's anchorPoint. When you set the position of the layer, you are then setting the location of the center of the layer in its superlayer's coordinate system. Because the position is relative to the anchorPoint of the layer, changing that anchorPoint while maintaining the same position moves the layer. So, you will have to set the anchorPoint before rendering the subview.


Also, for infinite repeat, you can avoid writing animationDidStop method, by using this property:

anim2.repeatCount = HUGE_VALF;

You need to set the position of the layer, on the Image View. Add this in the buttonPressed method:

//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]

that way, you can move the imageView around in the .xib, and the animation will take place the correct spot.

Edit: The solution by @Nishant is so much prettier..

Set the anchor of the layer so that it rotates around the correct centre, then immediately re-position it to account for the new anchor point (otherwise it will change its position):

    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)

With...

extension NSView {
var center: CGPoint {
    get {
        return CGPointMake(NSMidX(self.frame), NSMidY(self.frame))
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!