Search code examples
iphoneiosgraphicsscale

How to clip image in scale in iPhone?


I have a large sized image (2048*2048px), this image is shown as 320*320 on iPhone screen. I want to do this:

In my APP, user can open large sized image(e.g. 2048*2048), the image is shown as 320*320 on iPhone screen, and there is rectangle over the image, user can move the rectangle anywhere within image on iPhone screen, e.g. rectangle(100, 100, 300, 200), then I want to clip the original sized image within the rectangle area in scale.

I tried many ways,

UIImageView *originalImageView = [[UIImage View alloc] initWithImage:originalImage]];

CGRect rect = CGRectMake(100, 100, 300, 200);

UIImage *cropImage = [UIImage imageWithCGImage:CGImageCreateWithImageInRect([originalImageView.image CGImage], rect)];

But I got the cropImage is just 300*200 sized image, not scale properly.


Solution

  • How about doing this, it will preserve the original image quality

    CGSize bounds = CGSizeMake(320,320) // Considering image is shown in 320*320
    CGRect rect = CGRectMake(100, 100, 220, 200); //rectangle area to be cropped
    
    float widthFactor = rect.size.width * (originalImage.size.width/bounds.size.width);
    float heightFactor = rect.size.height * (originalImage.size.height/bounds.size.height);
    float factorX = rect.origin.x * (originalImage.size.width/bounds.size.width);
    float factorY = rect.origin.y * (originalImage.size.height/bounds.size.height);
    
    CGRect factoredRect = CGRectMake(factorX,factorY,widthFactor,heightFactor);
    UIImage *cropImage = [UIImage imageWithCGImage:CGImageCreateWithImageInRect([originalImage CGImage], factoredRect)];
    

    And most importantly if you want to crop image that imagePickerController returns, then this can be done by built in function as below,

    imagePickerController.allowsEditing = YES;