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

Raf*_*ski 11 cocoa-touch core-animation image-rotation ios

我想在左上角旋转图像,而不是中心.根据文档,我将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];
Run Code Online (Sandbox Code Playgroud)

radians() 定义如下:

static inline double radians (double degrees) {return degrees * M_PI/180;}
Run Code Online (Sandbox Code Playgroud)

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

Kru*_*lur 23

更改锚点会影响视图的位置.如果更改锚点并且想要将视图保持在当前位置,则需要更改视图的位置.使用类似这样的东西(取自此处:在(核心)动画的开始处跳转图层位置)来设置锚点并补偿位置变化:

-(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;
}
Run Code Online (Sandbox Code Playgroud)

另请参阅此处了解更多详细信息:更改我的CALayer的anchorPoint会移动视图