核心animation围绕点旋转

我想使一个IBOutlet围绕父视图中的特定点旋转,目前我只知道如何围绕一个锚点旋转它,但是,我想要在对象的图层外使用一个点。

旋转angular度是相对于从该点开始的设备航向而计算的。

- (void)viewDidLoad{ [super viewDidLoad]; locationManager=[[CLLocationManager alloc] init]; locationManager.desiredAccuracy = kCLLocationAccuracyBest; locationManager.headingFilter = 1; locationManager.delegate=self; [locationManager startUpdatingHeading]; [locationManager startUpdatingLocation]; compassImage.layer.anchorPoint=CGPointZero; } - (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading{ // Convert Degree to Radian and move the needle float oldRad = -manager.heading.trueHeading * M_PI / 180.0f; float newRad = -newHeading.trueHeading * M_PI / 180.0f; CABasicAnimation *theAnimation; theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.rotation"]; theAnimation.fromValue = [NSNumber numberWithFloat:oldRad]; theAnimation.toValue=[NSNumber numberWithFloat:newRad]; theAnimation.duration = 0.5f; [compassImage.layer addAnimation:theAnimation forKey:@"animateMyRotation"]; compassImage.transform = CGAffineTransformMakeRotation(newRad); NSLog(@"%f (%f) => %f (%f)", manager.heading.trueHeading, oldRad, newHeading.trueHeading, newRad); } 

我怎样才能旋转的UIImageView(x,y)的阿尔法?

为了围绕一个特定的点(内部或外部)旋转,你可以改变图层的锚点,然后应用一个正常的旋转变换animation,类似于我在这篇博客文章中所写的内容 。

您只需要注意,锚点也会影响图层在屏幕上的显示位置。 当您更改定位点时,还必须更改位置以使图层显示在屏幕上的相同位置。

假设图层已经放置在开始位置,并且旋转的点是已知的,则可以像这样计算锚点和位置(请注意,锚点位于图层边界的单位坐标空间中x和y的范围从0到1范围内)):

 CGPoint rotationPoint = // The point we are rotating around CGFloat minX = CGRectGetMinX(view.frame); CGFloat minY = CGRectGetMinY(view.frame); CGFloat width = CGRectGetWidth(view.frame); CGFloat height = CGRectGetHeight(view.frame); CGPoint anchorPoint = CGPointMake((rotationPoint.x-minX)/width, (rotationPoint.y-minY)/height); view.layer.anchorPoint = anchorPoint; view.layer.position = rotationPoint; 

然后,您只需将旋转animation应用到它,例如:

 CABasicAnimation *rotate = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"]; rotate.toValue = @(-M_PI_2); // The angle we are rotating to rotate.duration = 1.0; [view.layer addAnimation:rotate forKey:@"myRotationAnimation"]; 

只要注意,你已经改变了锚点,所以position不再在frame的中心,如果你应用其他变换(如比例尺),他们也将相对于锚点。

大卫的答案是迅速的3:

  let rotationPoint = CGPoint(x: layer.frame.width / 2.0, y: layer.frame.height / 2.0) // The point we are rotating around print(rotationPoint.debugDescription) let width = layer.frame.width let height = layer.frame.height let minX = layer.frame.minX let minY = layer.frame.minY let anchorPoint = CGPoint(x: (rotationPoint.x-minX)/width, y: (rotationPoint.y-minY)/height) layer.anchorPoint = anchorPoint; layer.position = rotationPoint;