我想让 IBOutlet 围绕父 View 中的特定点旋转, 目前我只知道如何围绕 anchor 旋转它,但是,我想使用对象层之外的点。
旋转角度是从该点开始相对于设备航向计算的。
- (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) 旋转 alpha?
最佳答案
要围绕特定点(内部或外部)旋转,您可以更改图层的 anchor ,然后应用类似于 what I wrote about in this blog post 的常规旋转变换动画。 .
您只需要注意 anchor 也会影响图层在屏幕上的显示位置。当您更改 anchor 时,您还必须更改位置以使图层出现在屏幕上的同一位置。
假设图层已经放置在它的起始位置并且旋转的点是已知的, anchor 和位置可以这样计算(注意 anchor 在图层的单位坐标空间中边界(意味着 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;
然后您只需对其应用旋转动画,例如:
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"];
请注意,您已经更改了 anchor ,因此 position
不再位于 frame
的中心,并且如果您应用其他变换(例如比例尺)它们也将相对于 anchor 。
关于ios - 核心动画围绕点旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22887629/