简体   繁体   中英

ios rotate image and zoom, so it fits original frame like in instagram

In instagram when you rotate image it zooms, so you cannot see those angled corners. Thats perfect.

This topic 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-box solution, some library that would include this function.

I know how to rotate or zoom image. I just don't know how much shall be the zoom after rotation according to the aspect ratio and angle.

I don't know of any library, but the following methods should provide what you need. Assume that you have a view of size contentSize , that you want to rotate through angle radians and scale to completely fill (with no "empty" corners) a view of size containerSize . The first method below will return (as a double ) the scale factor you should apply.

For completeness, the second method below will provide the scaling factor if you wish to rotate a view of size contentSize through angle radians and scale it to ensure if fits completely within the containerSize (so none of its corners extend beyond the edges).

Both methods assume that the two views have the same centre.

-(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 might use these 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM