How to rotate an layer at a specific anchor point without a skip?

后端 未结 1 1042
花落未央
花落未央 2021-02-08 04:52

I want to rotate a layer with an image at the top left corner, and not the center. According to the docs I set the anchorPoint property to [0, 1]. The view rotates

1条回答
  •  情话喂你
    2021-02-08 05:08

    Changing the anchor point affects the positioning of your view. You'll need to change the view's position if you change the anchor point and if you want to keep your view where it currently is. Use something like this (taken from here: Layer Position jumps at start of (Core) Animation) to set your anchor point and compensate position changes:

    -(void)setAnchorPoint:(CGPoint)anchorPoint forView:(UIView *)view
    {
        CGPoint newPoint = CGPointMake(view.bounds.size.width * anchorPoint.x, view.bounds.size.height * anchorPoint.y);
        CGPoint oldPoint = CGPointMake(view.bounds.size.width * view.layer.anchorPoint.x, view.bounds.size.height * view.layer.anchorPoint.y);
    
        newPoint = CGPointApplyAffineTransform(newPoint, view.transform);
        oldPoint = CGPointApplyAffineTransform(oldPoint, view.transform);
    
        CGPoint position = view.layer.position;
    
        position.x -= oldPoint.x;
        position.x += newPoint.x;
    
        position.y -= oldPoint.y;
        position.y += newPoint.y;
    
        view.layer.position = position;
        view.layer.anchorPoint = anchorPoint;
    }
    

    Also see here for more details: Changing my CALayer's anchorPoint moves the view

    0 讨论(0)
提交回复
热议问题