user3543085
user3543085

Reputation: 53

Cropping UIImage from pinch/Zoom state

I have been looking around to find a way to crop an image (imageView) inside ScrollView. What i need to achieve here is user pinch to zoom an image, (which is working great) and then able to crop ONLY the part of the image that is shown on the screen after the zoom. so in another words, if i have a series of number 1 to 10, user zoom it to see only number 4 and 5 and when user taps crop, i ONLY need image of 4 and 5 that was visible at the time of crop. I'm using this code...

- (UIImage *)croppedImageWithImage:(UIImage *)image zoom:(CGFloat)zoom
{
    CGFloat zoomReciprocal = 1.0f / zoom;
    CGRect croppedRect = CGRectMake(self.scrollView.contentOffset.x*zoom,
                                    self.scrollView.contentOffset.y*zoom,
                                    image.size.width * zoomReciprocal,
                                    image.size.height * zoomReciprocal);

    CGImageRef croppedImageRef = CGImageCreateWithImageInRect([image CGImage], croppedRect);

    UIImage* croppedImage = [[UIImage alloc] initWithCGImage:croppedImageRef scale:[image scale] orientation:[image imageOrientation]];

    CGImageRelease(croppedImageRef);

    return croppedImage;
}

This method crops the image however, the x and y values are incorrect... What do i have to do to get the correct x and y of my crop area?

FYI.. the image i'm trying to crop is 2200 * 3200, not sure if that would make any difference?

Upvotes: 1

Views: 1535

Answers (1)

user3543085
user3543085

Reputation: 53

I solved it!! here is the updated method for others who might come across this issue.

- (UIImage *)croppedImageWithImage:(UIImage *)image zoom:(CGFloat)zoom {
    CGFloat zoomReciprocal = 1.0f / zoom;
    CGFloat xOffset = image.size.width / self.scrollViewBackground.contentSize.width;
    CGFloat yOffset = image.size.height / self.scrollViewBackground.contentSize.height;

    CGRect croppedRect = CGRectMake(self.scrollViewBackground.contentOffset.x * xOffset,
                                    self.scrollViewBackground.contentOffset.y * yOffset,
                                    image.size.width * zoomReciprocal,
                                    image.size.height * zoomReciprocal);

    CGImageRef croppedImageRef = CGImageCreateWithImageInRect([image CGImage], croppedRect);
    UIImage *croppedImage = [[UIImage alloc] initWithCGImage:croppedImageRef scale:[image scale] orientation:[image imageOrientation]];
    CGImageRelease(croppedImageRef);
    return croppedImage;

}

Upvotes: 4

Related Questions