Search code examples
ioscore-graphicslinear-algebra

Is there a way to calculate the CGAffineTransform needed to transform a view from frame A to frame B?


Say, I have two CGRects, CGRect A and CGRect B. My UIView's frame is the same as CGRect B, but I want to create an animation showing the UIView transitioning from frame A to B.

I'm trying to do this by changing the transform property of the UIView, so I don't have to mess around with its frame too much. However, I need the CGAffineTransform to make this possible. What is the best way to calculate this transform?


Solution

  • I haven't been able to find a convenience method of any kind for this, so I resorted to tried and true matrix calculations to achieve this.

    Given a CGRect A and CGRect B, to calculate the transformation needed to go from A to B, do the following:

    CGAffineTransform transform = CGAffineTransformTranslate(CGAffineTransformIdentity, -A.origin.x, -A.origin.y);
    transform = CGAffineTransformScale(transform, 1/A.size.width, 1/A.size.height);
    transform = CGAffineTransformScale(transform, B.size.width, B.size.height);
    transform = CGAffineTransformTranslate(transform, B.origin.x, B.origin.y);