Cropping an UIImage

后端 未结 24 2109
轮回少年
轮回少年 2020-11-22 02:45

I\'ve got some code that resizes an image so I can get a scaled chunk of the center of the image - I use this to take a UIImage and return a small, square repre

24条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 03:44

    CGSize size = [originalImage size];
    int padding = 20;
    int pictureSize = 300;
    int startCroppingPosition = 100;
    if (size.height > size.width) {
        pictureSize = size.width - (2.0 * padding);
        startCroppingPosition = (size.height - pictureSize) / 2.0; 
    } else {
        pictureSize = size.height - (2.0 * padding);
        startCroppingPosition = (size.width - pictureSize) / 2.0;
    }
    // WTF: Don't forget that the CGImageCreateWithImageInRect believes that 
    // the image is 180 rotated, so x and y are inverted, same for height and width.
    CGRect cropRect = CGRectMake(startCroppingPosition, padding, pictureSize, pictureSize);
    CGImageRef imageRef = CGImageCreateWithImageInRect([originalImage CGImage], cropRect);
    UIImage *newImage = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:originalImage.imageOrientation];
    [m_photoView setImage:newImage];
    CGImageRelease(imageRef);
    

    Most of the responses I've seen only deals with a position of (0, 0) for (x, y). Ok that's one case but I'd like my cropping operation to be centered. What took me a while to figure out is the line following the WTF comment.

    Let's take the case of an image captured with a portrait orientation:

    1. The original image height is higher than its width (Woo, no surprise so far!)
    2. The image that the CGImageCreateWithImageInRect method imagines in its own world is not really a portrait though but a landscape (That is also why if you don't use the orientation argument in the imageWithCGImage constructor, it will show up as 180 rotated).
    3. So, you should kind of imagine that it is a landscape, the (0, 0) position being the top right corner of the image.

    Hope it makes sense! If it does not, try different values you'll see that the logic is inverted when it comes to choosing the right x, y, width, and height for your cropRect.

提交回复
热议问题