不用担心左上角可能更容易,而只需设置按钮的center
属性(而不是frame
属性)。计算左上角的偏移量并不难,但调整center
属性要直观得多,恕我直言。
或者,如果您不想调整center
或frame
坐标,您可以使用 Quartz 2D 围绕屏幕上的某个点旋转按钮:
因此,如果您将 QuartzCore.framework 链接到您的项目,您可以:
#import <QuartzCore/QuartzCore.h>
@interface ViewController ()
@property (nonatomic, strong) CADisplayLink *displayLink;
@property (nonatomic) CFTimeInterval startTime;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self rotateButtonAroundPoint];
}
- (void)rotateButtonAroundPoint
{
// the point about which I'm rotating and at what radius
CGPoint center = CGPointMake(self.view.bounds.size.width / 2.0, self.view.bounds.size.height / 2.0);
CGFloat radius = 100.0;
// now configure the button's layer accordingly
self.button.layer.anchorPoint = CGPointMake(0.5, 0.5 + radius / self.button.frame.size.height);
self.button.layer.position = center;
// just so I can see what I'm rotating this around
[self addCircleAt:center radius:5.0 color:[UIColor redColor]];
// turn on display link to animate it (better than `NSTimer` for animations)
[self startDisplayLink];
}
- (void)addCircleAt:(CGPoint)center radius:(CGFloat)radius color:(UIColor *)color
{
CAShapeLayer *layer = [CAShapeLayer layer];
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:0 endAngle:2.0 * M_PI clockwise:YES];
layer.path = [path CGPath];
layer.fillColor = [color CGColor];
[self.view.layer addSublayer:layer];
}
- (void)startDisplayLink
{
self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleDisplayLink:)];
self.startTime = CACurrentMediaTime();
[self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}
- (void)stopDisplayLink
{
[self.displayLink invalidate];
self.displayLink = nil;
}
- (void)handleDisplayLink:(CADisplayLink *)displayLink
{
CFTimeInterval elapsed = CACurrentMediaTime() - _startTime;
self.button.transform = CGAffineTransformMakeRotation(elapsed * 2.0 * M_PI / 5.0); // duration = 5.0 seconds
}
我怀疑仅更改center
/frame
或进行平移(而不是这种旋转)在计算上可能会更便宜,但是如果您希望按钮在旋转时实际旋转,这是一种选择,并且它具有一定的优雅性(只是设置position
和anchorPoint
旋转它,根本不用担心笛卡尔坐标)。