-->

How To Get A Perfect Position Of Rotating View?

2019-08-06 00:42发布

问题:

I am have one view and I am rotating that view using CABasicAnimation. Now my problem is that how I get a perfect position of that view while rotating. I have tried many type of codes but i can't got a perfect position during rotation of that view.

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"];

I am using this code for rotating my view.

I have also attached a one photo of my view.

Thank you In Advance Please Help If You Know.

回答1:

To get view's parameters during the animation you should use view.layer.presentationLayer

ADDED:

In order to get the coordinate of top left corner of the view, use the following code:

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

Resulting CGPoint will be the coordinate of the top left corner of your (rotated) view relative to its superview.



回答2:

Set the position of the layer that you what

[layer setPosition:endpoint];

Or you may also refer this CABasicAnimation rotate returns to original position