Search code examples
iosscreenshotareacgimage

CGImageCreateWithImageInRect incorrect area?


I am using this github image cropper: https://github.com/iosdeveloper/ImageCropper

In this image cropper, in the init method they have these lines:

CGRect rect;
        rect.size.width = image.size.width;
        rect.size.height = image.size.height;

        [imageView setFrame:rect];

Beforehand, I resize the image to the screens resolution not points. So if I leave the code above the way it is, my UIImage will not fill the UIImageView for some odd reason, and I have tried to adjust the contentModes also.

But if I adjust it to this (the size of the UIPopover that the image cropper is in):

[imageView setFrame:CGRectMake(0, 0, 320, 480)];

The UIImage will fill the UIPopover.

The real issue is here: If I zoom into a certain part of the image and execute the code below, it will take screenshot of the top left part of the UIImage no where near to where I have cropped the image to. Although it does abide by the scrollView's zoomScale.

Here is the screenshot code:

- (void)finishCropping {

    float zoomScale = 1.0 / [scrollView zoomScale];

    CGRect rect;
    rect.origin.x = [scrollView contentOffset].x * zoomScale;
    rect.origin.y = [scrollView contentOffset].y * zoomScale;
    rect.size.width = [scrollView bounds].size.width * zoomScale;
    rect.size.height = [scrollView bounds].size.height * zoomScale;

    CGImageRef cr = CGImageCreateWithImageInRect([[imageView image] CGImage], rect);

    UIImage *cropped = [UIImage imageWithCGImage:cr];

    CGImageRelease(cr);

    [delegate imageCropper:self didFinishCroppingWithImage:cropped];
}

Does anyone know why this is happening?

Thanks!


Solution

  • I think you have at first to use [UIImage imageWithCGImage:cr scale:self.scale orientation:self.imageOrientation] instead [UIImage imageWithCGImage:cr] to create UIImage, this will take off many problems with orientation and double check the width and height are in the right direction in rect.