【问题标题】:How To Get A Perfect Position Of Rotating View?如何获得完美的旋转视图位置?
【发布时间】:2023-08-25 18:09:02
【问题描述】:

我有一个视图,我正在使用CABasicAnimation 旋转该视图。 现在我的问题是我如何在旋转时获得该视图的完美位置。我尝试了许多类型的代码,但在该视图的旋转过程中我无法获得完美的位置。

CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
NSNumber *currentAngle = [CircleView.layer.presentationLayer valueForKeyPath:@"transform.rotation"];
rotationAnimation.fromValue = currentAngle;
rotationAnimation.toValue = @(50*M_PI);
rotationAnimation.duration = 50.0f;             // this might be too fast
rotationAnimation.repeatCount = HUGE_VALF;     // HUGE_VALF is defined in math.h so import it
[CircleView.layer addAnimation:rotationAnimation forKey:@"rotationAnimationleft"];

我正在使用此代码来旋转我的视图。

我还附上了一张我的观点的照片。

提前谢谢你,如果你知道的话,请帮忙。

【问题讨论】:

    标签: ios iphone rotation position cabasicanimation


    【解决方案1】:

    要在动画期间获取视图的参数,您应该使用view.layer.presentationLayer

    添加:

    为了获取视图左上角的坐标,使用以下代码:

    - (CGPoint)currentTopLeftPointOfTheView:(UIView *)view
    {
        CGRect rect = view.bounds;
        rect.origin.x = view.center.x - 0.5 * CGRectGetWidth(rect);
        rect.origin.y = view.center.y - 0.5 * CGRectGetHeight(rect);
    
        CGPoint originalTopLeftCorner = CGPointMake(CGRectGetMinX(rect), CGRectGetMinY(rect));
        CGPoint rectCenter = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
        CGFloat radius = sqrt(pow(rectCenter.x - originalTopLeftCorner.x, 2.0) + pow(rectCenter.y - originalTopLeftCorner.y, 2.0));
    
        CGFloat originalAngle = M_PI - acos((rectCenter.x - originalTopLeftCorner.x) / radius);
    
        CATransform3D currentTransform = ((CALayer *)view.layer.presentationLayer).transform;
        CGFloat rotation = atan2(currentTransform.m12, currentTransform.m11);
    
        CGFloat resultAngle = originalAngle - rotation;
        CGPoint currentTopLeftCorner = CGPointMake(round(rectCenter.x + cos(resultAngle) * radius), round(rectCenter.y - sin(resultAngle) * radius));
    
        return currentTopLeftCorner;
    }
    

    生成的CGPoint 将是(旋转的)视图左上角相对于其父视图的坐标。

    【讨论】:

    • 完美位置是什么意思?
    • 所以你想确定视图左上角的坐标,对吧?
    • 我想要一个新的 (x,y) 旋转视图位置
    • 将在几分钟内将其作为答案发布
    【解决方案2】:

    设置你想要的图层的位置

    [layer setPosition:endpoint];
    

    或者你也可以参考这个CABasicAnimation rotate returns to original position

    【讨论】:

    • 对不起,我不想要原来的位置,请理解问题
    • 我想要一个完美的 pisition 而视图正在旋转。
    • 你想要完美的位置能多解释一下
    • 每秒钟每次我想要那个视图的位置
    • 当视图旋转时
    最近更新 更多