iOS_UIImage_图片剪切

- (UIImage *)imagecutWithRect:(CGRect)rect {

    CGImageRef subImageRef = CGImageCreateWithImageInRect(self.CGImage, rect);
    
    CGRect smallRect = CGRectMake(0, 0, CGImageGetWidth(subImageRef), CGImageGetHeight(subImageRef));
    
    // 开启图形上下文
    UIGraphicsBeginImageContext(smallRect.size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextDrawImage(context, smallRect, subImageRef);
    
    UIImage * image = [UIImage imageWithCGImage:subImageRef];
    
    // 关闭图形上下文
    UIGraphicsEndImageContext();
    
    CGImageRelease(subImageRef);
    
    return image;
}

使用

- (UIImageView *)imageView {
    if (_imageView == nil) {
        self.imageView = [[UIImageView alloc] init];
        self.imageView.backgroundColor = [UIColor redColor];
                
        UIImage * image = [UIImage imageNamed:@"1.jpg"];
        // 截取原图中间300*300
        CGFloat cutImageWH = 300;
        CGFloat cutImage_x = (image.size.width - 300) / 2;
        CGFloat cutImage_y = (image.size.height - 300) / 2;
        
        self.imageView.image = [image imagecutWithRect:CGRectMake(cutImage_x, cutImage_y, cutImageWH, cutImageWH)];
    } return _imageView;
}

github地址: https://github.com/mancongiOS/UIImage.git 

原文地址:https://www.cnblogs.com/mancong/p/6138057.html