【作者前言】:13年入圈,分享些本人工作中遇到的点点滴滴那些事儿,17年刚开始写博客,高手勿喷!以分享交流为主,欢迎各路豪杰点评改进!
1.应用场景:
2.实现目标:
对一张图片的指定的部分进行剪切,剪切后形成新的图片
3.代码说明:
①剪切
#pragma mark -
#pragma mark - yp_imagecutWithOriginalImage: withCutRect: 根据指定的范围剪切图片中的一部分
/** originalImage:原图片 rect:需要剪切的位置*/
- (UIImage *)yp_imagecutWithOriginalImage:(UIImage *)originalImage withCutRect:(CGRect)rect {
CGImageRef subImageRef = CGImageCreateWithImageInRect(originalImage.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;
}
②+按照一定尺寸重绘图片
#pragma mark -
#pragma mark - yp_imageWithOriginalImage: withScaleSize: 将图片重新按照一定的尺寸绘制出来
- (UIImage *)yp_imageWithOriginalImage:(UIImage *)originalImage withScaleSize:(CGSize)size {
UIGraphicsBeginImageContext(size);
[originalImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}