Crop Landscape Image Dynamically

偶尔善良 提交于 2019-12-08 03:49:27

Well, as @HDdeveloper rightly said, you can use CGImageCreateWithImageInRect. This take 2 params, the first is the whole image, the second is the frame that you want to crop (so probably the frame of your red imageView).
The problem is that if you're targeting for both retina/non retina; if your whole image is an image @2x and you want to crop the image with the red imageview frame you have to double your frame to get the right screenshot.
So you can try with this method:

//Define the screen type:
#define isRetinaDisplay [[UIScreen mainScreen] respondsToSelector:@selector(displayLinkWithTarget:selector:)] && ([UIScreen mainScreen].scale == 2.0)

- (UIImage*)cropInnerImage:(CGRect)rect {
    //Take a screenshot of the whole image
    UIGraphicsBeginImageContextWithOptions(self.view.frame.size, NO, 0.0);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage* ret = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGRect rct;
    //Double the frame if you're in retina display
    if (isRetinaDisplay) {
        rct=CGRectMake(rect.frame.origin.x*2, rect.frame.origin.y*2, rect.size.width*2, rect.size.height*2);
    } else {
        rct=rect;
    }
    //Crop the image from the screenshot
    CGImageRef imageRef = CGImageCreateWithImageInRect([ret CGImage], rct);
    UIImage *result = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    //Save and open the result images with Preview.app
    [UIImagePNGRepresentation(result) writeToFile: @"/tmp/testCrop.png" atomically: YES];
    system("open /tmp/testCrop.png");
    [UIImagePNGRepresentation(ret) writeToFile: @"/tmp/testRet.png" atomically: YES];
    system("open /tmp/testRet.png");
    //
    return result;
}

Where the rect parameter must be your red image frame, and self.view.frame must be the equal to the wholeImageView.frame. You can skip the last 4 lines, these are just to see in your Mac what you're cropping.

PS: i use this method to crop an image and set it as background of UIView, this is the reason i have to double the frame.

You can use CGImageRef pass your rect in the whole image. Then call this on button click

UIImage* whole = [UIImage imageNamed:@"9.png"]; //I uses this image
    CGImageRef cgImg = CGImageCreateWithImageInRect(whole.CGImage, CGRectMake(x, y, incX, incY));
    UIImage* part = [UIImage imageWithCGImage:cgImg];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!