简体   繁体   中英

How to get the exact bounding box of UIImage from rotated UIImageView

Iam applying transformations to the UIImageView(Rotate, scale and invert) and I want to save the UIImage from rotated UIImageView. So How can I get the exact bounding box of the UIImage to draw the UIImage View.

    CGAffineTransform transform = selImageView.transform;
    CGPathRef rotatedImageRectPath = CGPathCreateWithRect(selImageView.frame, &transform);
    CGRect boundingBox = CGPathGetBoundingBox(rotatedImageRectPath);

    CGSize rotatedSize = boundingBox.size;
    UIGraphicsBeginImageContextWithOptions(rotatedSize, NO, 0.0f);

    // Move the origin to the middle of the image so we will rotate and scale around the center.
    CGContextTranslateCTM(UIGraphicsGetCurrentContext(), rotatedSize.width/2, rotatedSize.height/2);
//    CGContextSetFillColorWithColor(UIGraphicsGetCurrentContex(),[UIColor clearColor].CGColor);
    //Rotate the image context using tranform
    CGContextConcatCTM(UIGraphicsGetCurrentContext(), selImageView.transform);
    // Now, draw the rotated/scaled image into the context
    CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1.0, -1.0);
    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(-aTransImage.size.width / 2, -aTransImage.size.height / 2, aTransImage.size.width, aTransImage.size.height), [aTransImage CGImage]);

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;

Check out this app. It does most of the task you are trying to perform. you can analyze the code for working.

https://github.com/heitorfr/ios-image-editor

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