首页 文章

如何在没有跳过的情况下在特定锚点旋转图层?

提问于
浏览
11

我想在左上角旋转图像,而不是中心 . 根据文档,我将 anchorPoint 属性设置为[0,1] . 视图在我的示例中旋转50°,但在它开始动画之前,视图会跳转到屏幕上的另一个点 .

self.shakeTag.layer.anchorPoint = CGPointMake(0.0f, 1.0f);
[UIView beginAnimations:@"rotate" context:nil];
[self.shakeTag.layer setTransform:
  CATransform3DRotate(CATransform3DIdentity,
  radians(50.0), 0.0f, 0.0f, 1.0f)];
[UIView commitAnimations];

radians() 的定义如下:

static inline double radians (double degrees) {return degrees * M_PI/180;}

当我使用4倍大小并且具有大量透明像素的图像时,我可以在默认锚点[0.5,0.5]处旋转它,但我不想浪费空间用于不可见像素 . 任何想法如何防止图层在旋转发生之前跳跃?

1 回答

  • 23

    更改锚点会影响视图的位置 . 如果您更改锚点并且想要将视图保持在当前位置,则为'll need to change the view'的位置 . 使用类似这样的东西(取自这里:Layer Position jumps at start of (Core) Animation)来设置锚点并补偿位置变化:

    -(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;
    }
    

    另请参阅此处了解更多详情:Changing my CALayer's anchorPoint moves the view

相关问题