美文网首页
CGContextDrawImage(context, rect

CGContextDrawImage(context, rect

作者: LX2014 | 来源:发表于2017-09-08 17:09 被阅读93次

在截取头像时,需要获取一张图片的指定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;
}

相关文章

网友评论

      本文标题:CGContextDrawImage(context, rect

      本文链接:https://www.haomeiwen.com/subject/pdhnjxtx.html