在截取头像时,需要获取一张图片的指定rect内的图片,如果传入的rect在原图片之外那么就会出现截取的图片拉伸的情况,所以这里rect要做边界判断:
- (UIImage *)thumbImageFromImage:(UIImage *)image imRect:(CGRect)rect {
if (![image isKindOfClass:[UIImage class]]) {
return nil;
}
CGImageRef imageRef = image.CGImage;
CGImageRef subImageRef = CGImageCreateWithImageInRect(imageRef, rect);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextDrawImage(context, rect, subImageRef);
UIImage* smallImage = [UIImage imageWithCGImage:subImageRef];
UIGraphicsEndImageContext();
CGImageRelease(subImageRef);
return smallImage;
}