batuman
batuman

Reputation: 7304

Image cropping from UIImageView

I have a UIImageView with size (0,0,414,471). The image with size (0,0,1236,1242) is displayed with UIViewContentModeScaleAspectFit mode in the UIImageView. So the image is nicely displayed. Then I make a rectangle (0,0,100,100) on the image and I like to crop it. Even though the rectangle covered (100,100) on the UIImageView, on the actual image size, (100,100) does not cover the size as shown on the UIImageView. So I make xratio (actual width/display width) and yratio(actual height/display height), then I multiply the rectangle size, to all x,y,width and height of the rectangle. This approach looks like I can crop the area as close as possible as shown on the UIImageView. But still have a bit of area offset and distortion. What could be the best way to crop in this scenario? My code is shown below

- (void)saveCroppedImage:(UIImage *)image withcroppedRectangle:(CGRect)clippedRect
{
    float xratio = image.size.width/displayWidth;
    float yratio = image.size.height/displayHeight;
    // Crop logic
    clippedRect.origin.x *= xratio;
    clippedRect.origin.y *= yratio;
    clippedRect.size.width *= xratio;
    clippedRect.size.height *= yratio;

    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], clippedRect);
    UIImage * croppedImage = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    NSString *imageName =@"Documents/";
    imageName = [imageName stringByAppendingString:[CurrentToddlerProfile getUserID]];
    imageName = [imageName stringByAppendingString:@".png"];
    NSString  *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:imageName];
    // Write image to PNG
    [UIImagePNGRepresentation(croppedImage) writeToFile:pngPath atomically:YES];
    // Create file manager
//    NSFileManager *fileMgr = [NSFileManager defaultManager];
//    NSError *error;
//    // Point to Document directory
//    NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
//    // Write out the contents of home directory to console
//    NSLog(@"Documents directory: %@", [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);

}

Upvotes: 0

Views: 105

Answers (1)

Moose
Moose

Reputation: 2737

Are you sure you need two ratios ? If you want your image to have the right proportions, you should use only one ratio.

If you need to fill a rectangle ( Even if UIImageView does it for you ), then first compute the ratio on x axis. Compute the scaled height using this ratio, if it is smaller than the height you need to cover, then compute the ratio on y axis.

Finally, the ratio just computed is the one to use to scale your image.

Upvotes: 1

Related Questions