工作中,有些需求需要我们提供四四方方的图片、或者定好尺寸的图片,一般情况下我们可以设置UIImageView
的contentMode
为UIViewContentModeScaleAspectFill
时(imgView.contentMode = UIViewContentModeScaleAspectFill;
)可以自动截取掉多余的某两端的边缘图,而且图片也不被拉伸。但这个也只能做到图片两端的切除并显示,而且只在UIImageView
上面显示的时候有效,并没有真实的切割图片。
如果想要随心所欲的去切割图片。获取图片上任何一个位置的某一块,那就要用CGImageRef
来对图片底层(CGImage)处理一下做一下处理。代码如下:
/* 根据 location位置 subSize大小 返回一个新的子image**/
- (UIImage *)subImageFromImage:(UIImage *)image origin:(CGPoint)location size:(CGSize)subSize{
CGFloat screenScale = [UIScreen mainScreen].scale;
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(location.x, location.y, subSize.width * screenScale, subSize.height * screenScale));
UIImage *subImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return subImage;
}