2

我正在尝试围绕其中心旋转 NSView。但即使我更改了锚点,NSView 也会继续围绕其左上角旋转。只是一个精度:我正在使用 OSX 10.8.5。

在此先感谢您的帮助。

这是我的代码:

// myView.m
- (id)initWithFrame:(NSRect)rect
{
    if(self = [super initWithFrame:(NSRect)rect])
    {
        self.frame = rect;
        [self setWantsLayer:YES];
        self.layer.backgroundColor = [NSColor whiteColor].CGColor;
        self.layer.borderColor = [NSColor grayColor].CGColor;
        self.layer.borderWidth = 1.0;

        NSView *aView = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 50, 50)];
        [aView setWantsLayer:YES];
        aView.layer.backgroundColor = [NSColor redColor].CGColor;
        aView.layer.anchorPoint = CGPointMake(0.5, 0.5);

        [self addSubview:aView];

        CABasicAnimation *rotateAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
        rotateAnimation.byValue = [NSNumber numberWithFloat:2*M_PI];
        rotateAnimation.duration = 4;
        rotateAnimation.repeatCount = INFINITY;

        [aView.layer addAnimation:rotateAnimation forKey:@"rotationAnimation"];
    }
}

编辑 30-11-2018 :我设法使用图层获得居中旋转:

// myView.m
- (id)initWithFrame:(NSRect)rect
{
    if(self = [super initWithFrame:(NSRect)rect])
    {
        self.frame = rect;
        [self setWantsLayer:YES];
        self.layer.backgroundColor = [NSColor whiteColor].CGColor;
        self.layer.borderColor = [NSColor grayColor].CGColor;
        self.layer.borderWidth = 1.0;

        NSView *aView = [[NSView alloc] init];
        [aView setWantsLayer:YES];
        aView.layer.backgroundColor = [NSColor redColor].CGColor;
        aView.layer.bounds = CGRectMake(0, 0, 50, 50);
        aView.layer.frame = CGRectMake(0, 0, 50, 50);
        aView.layer.anchorPoint = CGPointMake(0.5, 0.5);
        aView.layer.position = CGPointMake(0, 0);

        [self.layer addSublayer:aView.layer];

        CABasicAnimation *rotateAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
        rotateAnimation.byValue = [NSNumber numberWithFloat:2*M_PI];
        rotateAnimation.duration = 4;
        rotateAnimation.repeatCount = INFINITY;

        [aView.layer addAnimation:rotateAnimation forKey:@"rotationAnimation"];
    }
}
4

1 回答 1

0

如果要旋转视图,可以执行以下操作:

-(void)rotateByCenter:(NSView*)aView {

[aView setWantsLayer:YES];
aView.layer.anchorPoint = CGPointMake(0.5, 0.5);
aView.layer.position = CGPointMake(aView.frame.origin.x + aView.frame.size.width/2.,aView.frame.origin.y + aView.frame.size.height/2.) ;

CABasicAnimation *rotateAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
rotateAnimation.byValue = [NSNumber numberWithFloat:2*M_PI];
rotateAnimation.duration = 20;
rotateAnimation.repeatCount = INFINITY;

[aView.layer addAnimation:rotateAnimation forKey:@"rotationAnimation"]; }
于 2019-03-22T11:43:45.390 回答