ios - 核心动画围绕点旋转

标签 ios objective-c core-animation

我想让 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/

相关文章:

iphone - 如何将 Core Animation 框架添加到我的 Xcode 项目中?

ios - iOS 中除了旋转之外的暂停和恢复动画?

iOS - 从 ViewController 调用 App Delegate 方法

ios - 将代码从 obj-c 转换为 Swift 的问题

objective-c - 自定义框架中的错误 "No known class method for selector ' Hello :'"

ios - Xcode不会自动创建桥接头?

ios - 如何将镜像添加到 2d Box 角

ios - 重命名 xcdatamodel 文件

ios - 忽略 IB 中的模棱两可的布局警告

ios - NS日历日期错误