Core Animation rotation around point

后端 未结 2 1568
庸人自扰
庸人自扰 2021-01-06 12:28

I would like to make an IBOutlet rotate around a specific point in the parent view, currently i only know how to rotate it around an anchor point, however, i want to use a p

相关标签:
2条回答
  • 2021-01-06 12:44

    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.

    0 讨论(0)
  • 2021-01-06 12:50

    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;
    
    0 讨论(0)
提交回复
热议问题