【问题标题】:Why does my view jump when setting the layer anchorPoint in an animation block?为什么在动画块中设置图层锚点时我的视图会跳转?
【发布时间】:2012-05-15 03:26:36
【问题描述】:

我有一个 UIPanGestureRecognizer 附加到我的 iOS 应用程序中的视图。我从Touches sample app 复制了用于平移处理程序的代码。当手势开始时,我的代码:

  • 记录原始锚点和中心。
  • 将锚点和中心更改为围绕用户的手指,如下所示:

    CGPoint locationInView = [gestureRecognizer locationInView:target];
    CGPoint locationInSuperview = [gestureRecognizer locationInView:target.superview];
    target.layer.anchorPoint = CGPointMake(
        locationInView.x / target.bounds.size.width,
        locationInView.y / target.bounds.size.height
    );
    target.center = locationInSuperview;
    

随着手势的进行,平移处理程序不断改变中心以跟踪手指移动。到目前为止一切顺利。

当用户放手时,我希望视图动画回到其原始起点。执行此操作的代码如下所示:

[UIView animateWithDuration:2 delay:0 options:UIViewAnimationCurveEaseOut animations:^{
    target.center            = originalCenter;
    target.layer.anchorPoint = originalAnchorPoint;
}];

这确实将视图动画化回其原始起点。但是,在动画开始之前,视图会跳转到 UI 中的不同位置。 IOW,放手,它跳起来,然后动画回到它所属的地方。

我想也许我需要在动画之外设置锚点和中心,也许将中心设置为超级视图中的位置,比如手势开始时,但这似乎没有区别。

我在这里缺少什么?用户放手时如何防止跳转?

【问题讨论】:

标签: cocoa-touch animation uiview cglayer


【解决方案1】:

我怀疑有两个问题没有尝试你在做什么:

更改锚点会改变视图/图层的位置。 为了在不修改位置的情况下更改锚点,您可以使用类似这样的一些帮助器:

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

您的动画将锚点设置回其原始值。 您应该使用上面的帮助器来重置锚点。这确保了视图在更改锚点时不会移动。您必须在动画之外执行此操作。然后,使用动画块更改视图的中心并将其动画到您想要的位置。

【讨论】:

  • 我以前试过这个,但也许我没有做对。今晚会再试一次。谢谢!
  • 好吧,这使它跳转到屏幕的完全不同的部分,但它仍然会跳转。:-( 试图确定它是否与我设置事物的顺序有关:视图的中心、锚点和变换。
  • 答案是“是的!”我正在设置中心,然后是锚点,然后是变换。我已将其更改为设置锚点(使用助手),然后是变换,最后是中心,现在它工作得完全正确。呸!感谢您对这个功能的提醒,我只需要再摆弄一下。
猜你喜欢
  • 2012-08-16
  • 1970-01-01
  • 1970-01-01
  • 2014-03-28
  • 2014-04-22
  • 1970-01-01
  • 2020-11-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多