# Ios rotate the image and zoom so it fits the original frame like in instagram

In the case that you rotate the image, it enlarges, so you cannot see the corners. It's fine.

This section is discussed here: https://math.stackexchange.com/questions/61005/resizing-a-rectangle-to-always-fit-into-its-unrotated-space

I wonder if there is any out-of-the-box solution, some kind of library that will include this feature.

I know how to rotate or scale an image. I just don't know how much scaling should be after rotation according to aspect ratio and angle.

+3

source to share

I don't know of any libraries, but the following methods should provide what you need. Suppose you have a dimension view `contentSize`

that you want to rotate radially `angle`

and scaled to completely fill (no empty corners) the dimension view `containerSize`

. The first method below returns (how `double`

) the scale factor that you must apply.

For completeness, the second method below will provide a scaling factor if you want to rotate the dimension view `contentSize`

in `angle`

radians and scale it to make sure it fits completely inside `containerSize`

(so none of its corners go out of bounds).

Both methods assume both views have the same center.

``````-(double)scaleToFill:(CGSize)containerSize withSize:(CGSize)contentSize atAngle:(double)angle {
double theta = fabs(angle - 2*M_PI*truncf(angle/M_PI/2) - M_PI);
if (theta > M_PI_2) {
theta = fabs(M_PI - theta);
}
double h = contentSize.height;
double H = containerSize.height;
double w = contentSize.width;
double W = containerSize.width;
double scale1 = (H*cos(theta) + W*sin(theta))/h;
double scale2 = (H*sin(theta) + W*cos(theta))/w;
double scaleFactor = MAX(scale1, scale2);
return scaleFactor;
}

-(double)scaleToFit:(CGSize)contentSize atAngle:(double)angle withinSize:(CGSize)containerSize {
double theta = fabs(angle - 2*M_PI*truncf(angle/M_PI/2) - M_PI);
if (theta > M_PI_2) {
theta = fabs(M_PI - theta);
}
double h = contentSize.height;
double H = containerSize.height;
double w = contentSize.width;
double W = containerSize.width;
double scale1 = H/(h*cos(theta) + w*sin(theta));
double scale2 = W/(h*sin(theta) + w*cos(theta));
double scaleFactor = MIN(scale1, scale2);
return scaleFactor;
}
```

```

You can use them with something like:

``````double scaleFactor = [self scaleToFill:self.containerView.bounds.size withSize:self.rotatedView.bounds.size atAngle:self.currentAngle];
CGAffineTransform rotation = CGAffineTransformMakeRotation(self.currentAngle);
CGAffineTransform scaledRotation = CGAffineTransformScale(rotation, scaleFactor, scaleFactor);
self.rotatedView.transform = scaledRotation;
```

```
+4

source

All Articles