Core Animation rotation around point

会有一股神秘感。 提交于 2019-12-01 08:03:20

For rotating around a specific point (internal or external) you can change the anchor point of the layer and then apply a regular rotation transform animation similar to what I wrote about in this blog post.

You just need to be aware that the anchor point also affects where the layer appears on the screen. When you change the anchor point you will also have to change the position to make the layer appear in the same place on the screen.

Assuming that the layer is already placed in it's start position and that the point to rotate around is known, the anchor point and the position can be calculated like this (note that the anchor point is in the unit coordinate space of the layer's bounds (meaning that x and y range from 0 to 1 within the bounds)):

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; 

Then you simply apply a rotation animation to it, for example:

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"];

Just note that you have changed the anchor point so the position is no longer in the center of the frame and if you apply other transforms (such as a scale) they will also be relative to the anchor point.

Translated David's answer to swift 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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!