【发布时间】:2018-11-26 08:35:18
【问题描述】:
我正在尝试围绕其中心旋转 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"];
}
}
2018 年 11 月 30 日编辑:我设法使用图层获得居中旋转:
// 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"];
}
}
【问题讨论】:
-
非常有用的例子!对于初学者,我喜欢添加两件事:1.)它需要添加 Quartz 框架库才能运行。 2.) 使用 Jeff 的示例代码,必须将 myView 的 View 添加到任何窗口。
标签: nsview cabasicanimation anchorpoint