简体   繁体   中英

How to rotate NSButton in clockwise direction from its center point in Cocoa?

I want to set animation for NSButton in my mac application.

I followed the below link for the same, but below code is working for iOS, not for Mac.

How to rotate a flat object around its center in perspective view?

What I want to achieve:

Basically, I want to rotate an image clockwise from the center point of the image just like the above code works for iOS. 以下结果来自我想要的iOS。

Issue currently having:

In Mac app, the image is rotating from its corner point, not from the center.

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    animation.fromValue = [NSNumber numberWithFloat:0];
    animation.toValue = [NSNumber numberWithFloat:2 * M_PI];
    animation.duration = 1.0;
    animation.repeatCount = INFINITY;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    [btnScan setWantsLayer:YES];
    [btnScan.layer addAnimation:animation forKey:@"transform.rotation.z"];

这是我目前在Mac应用程序中得到的结果。

The point around which rotation occurs is affected by the layer's position and anchorPoint properties, see Anchor Points Affect Geometric Manipulations . The default values for these properties do not appear to match the documentation, at least under macOS 10.11 and whichever version you used.

Try setting them by adding four lines as follows:

[btnScan setWantsLayer:YES];

CALayer *btnLayer = btnScan.layer;
NSRect frame = btnLayer.frame;
btnLayer.position = NSMakePoint(NSMidX(frame), NSMidY(frame)); // position to centre of frame
btnLayer.anchorPoint = NSMakePoint(0.5, 0.5); // anchor point to centre - specified in unit coordinates

[btnScan.layer addAnimation:animation forKey:@"transform.rotation.z"];

It doesn't actually matter in which order you set these properties the result should be an image rotation around the centre point of the button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM