Cropping an UIImage

后端 未结 24 2128
轮回少年
轮回少年 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:43

    Heads up: all these answers assume a CGImage-backed image object.

    image.CGImage can return nil, if the UIImage is backed by a CIImage, which would be the case if you created this image using a CIFilter.

    In that case, you might have to draw the image in a new context, and return that image (slow).

    UIImage* crop(UIImage *image, rect) {
        UIGraphicsBeginImageContextWithOptions(rect.size, false, [image scale]);
        [image drawAtPoint:CGPointMake(-rect.origin.x, -rect.origin.y)];
        cropped_image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return cropped_image;
    }
    

提交回复
热议问题