简体   繁体   中英

Crop Image using CGRect

I have been trying to do this since forever. I have a camera overlay. I want to get my final image to be the part of the image viewable from the in-built camera. What I did was make CGRect with dimensions equal to the square in the camera. Then I tried cropping it using this function.

- (UIImage *)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect
{
    CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);

    UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);

    return croppedImage;
}

I called it like this

CGRect rect = CGRectMake(10, 72, 300, 300);

UIImage *realImage = [self imageByCropping:[self.capturedImages objectAtIndex:0] toRect:rect];

What I get is a bad quality image with the wrong orientation.

::EDIT::

With Nitin's answer I can crop the correct part of the screen but the problem is it crops the view that follows the camera view, 'the confirmation view'. I suspect this is because Nitin's code uses

UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();

and because the ViewController in which all this is happening because the View Controller for the Confirmation View is the Controller in which this code is being executed. I will try to explain this with a small map

CameraOverlay.xib(it uses this xib to create an overlay) <===== CameraOverlayViewController ---------> ConfirmationView

So when first the ViewController is evoked(button on Tab bar), it opens the camera(UIImagePickerController) with an overlay over it. Then once user clicks an image, the image is shown on the ConfirmationView.

What I think is happening is when UIGraphicsBeginImageContextWithOptions(self.view.frame.size, YES, 1.0); [self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext(); these lines are being executed, the View at that time is ConfirmationView.

Note: I call the function in

(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info method.

Refer Drawing and printing Guide .

The default coordinate system is different between CoreGraphics and UIKit. I think your issue is because of this fact.

Using these may help you solve the issue

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context , 0.0, rect.size.height);
CGContextScaleCTM(context , 1.0, -1.0);

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