在 iOS 开发过程中,对图片的处理不仅仅局限于显示、渲染样式,还常常遇到对view指定区域截图,以及对图片的压缩、拉伸等操作。下面我们介绍一下类似的操作过程:
1. 在view中截取指定区域
+ (UIImage *)captureView:(UIView *)view atRect:(CGRect)rect {
UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, [UIScreen mainScreen].scale);
//UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);
CGContextRef context = UIGraphicsGetCurrentContext();
if (context == NULL) {
return nil;
} else {
CGContextSaveGState(context);
UIRectClip(rect);
[view.layer renderInContext:context];
CGContextRestoreGState(context);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
// UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);
// CGContextRef context = UIGraphicsGetCurrentContext();
// if (context == NULL) {
// return nil;
// } else {
// CGContextSaveGState(context);
// UIRectClip(rect);
// CGContextTranslateCTM(context, -rect.origin.x, -rect.origin.y);
// [view snapshotViewAfterScreenUpdates:YES];
// if([view respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) {
// [view drawViewHierarchyInRect:rect afterScreenUpdates:NO];
// } else {
// [view.layer renderInContext:context];
// }
//
// CGContextRestoreGState(context);
// UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// UIGraphicsEndImageContext();
//
// return image;
// }
}
- 对整个view进行截图,最简单的操作如下:
UIGraphicsBeginImageContextWithOptions(CGSizeMake(CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)), YES, 0.0);
[self.view drawViewHierarchyInRect:self.view.bounds afterScreenUpdates:NO];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
- 方法说明
// size 是指绘图的上下文的宽高,即画布的大小
// opaque 画布是否透明,YES: 画布背景为黑色 NO: 画布背景为白色
// scale 绘制图片的像素比,决定所绘图的清晰度,0.0为默认屏幕缩放比
UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale);
// 注意:该方法针对view,将绘制整个view
// rect 是被截图的整个view绘制至目标画布的frame(相当于以画布为父view)
// afterUpdates 截图的瞬间是否将屏幕当前的变更渲染进去
- (BOOL)drawViewHierarchyInRect:(CGRect)rect afterScreenUpdates:(BOOL)afterUpdates;
// 作用于CALayer层,将其layer渲染至当前context中
- (void)renderInContext:(CGContextRef)ctx;
// 注:
// renderInContext 是view的layer渲染到当前的上下文中;
// drawViewHierarchyInRect 是对view进行一个快照,并将快照绘制到画布上。
注:通过UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale)
和drawViewHierarchyInRect
的配合来截取并渲染出来的图片位置和大小,是由前者的size和后者的rect共同决定的。即,画布相当于父view,其尺寸为size,截图绘制到画布中的位置和尺寸为rect。
想试一试的同学,可以创建一个demo,取不同的size和rect值,来观察画布和截图的位置。也可以试着将画布和截图完全吻合,即将截图完整的渲染出来,这并不难。
2. 裁剪图片
裁剪图片就是对当前的图片按照指定的大小范围生成一个新的图片。需要注意的是如果当前显示图片是2倍图或者3倍图,要么可能尺寸不对,要么截出来的图片很模糊,因此,需要在截图前调整rect值。
// 方式1
- (UIImage *)clipImage:(UIImage *)image toRect:(CGRect)rect {
rect.origin.x *= image.scale;
rect.origin.y *= image.scale;
rect.size.width *= image.scale;
rect.size.height *= image.scale;
CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage, rect);
UIImage *newImage = [UIImage imageWithCGImage:imageRef scale:clipImage.scale orientation:UIImageOrientationUp];
CGImageRelease(imageRef);
return newImage;
}
// 方式2
- (UIImage *)clipImage:(UIImage *)image toWidth:(CGFloat)targetWidth {
CGSize imageSize = image.size;
CGFloat Originalwidth = imageSize.width;
CGFloat Originalheight = imageSize.height;
CGFloat targetHeight = Originalheight / Originalwidth * targetWidth;
UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
[image drawInRect:CGRectMake(0,0,targetWidth, targetHeight)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
3. 压缩图片
- (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size
{
UIImage *OriginalImage = image;
NSData * data = UIImageJPEGRepresentation(image, 1.0);
CGFloat dataKBytes = data.length/1000.0;
CGFloat maxQuality = 0.9f;
// 若首次压缩不<100k, 则减小尺寸并重新压缩
while (dataKBytes > size)
{
while (dataKBytes > size && maxQuality > 0.1f)
{
maxQuality = maxQuality - 0.1f;
data = UIImageJPEGRepresentation(image, maxQuality);
dataKBytes = data.length / 1000.0;
if(dataKBytes <= size )
{
return data;
}
}
OriginalImage =[self compressOriginalImage:OriginalImage toWidth:OriginalImage.size.width * 0.8];
image = OriginalImage;
data = UIImageJPEGRepresentation(image, 1.0);
dataKBytes = data.length / 1000.0;
maxQuality = 0.9f;
}
return data;
}
注:UIImageJPEGRepresentation 两个参数:图片引用 和压缩系数,而 UIImagePNGRepresentation 只需图片引用作为参数。在实际使用过程中,UIImagePNGRepresentation(UIImage* image) 一般要比UIImageJPEGRepresentation(UIImage* image, 1.0) 返回的图片数据量大,在处理图片时,若对图片质量要求不高,则建议使用UIImageJPEGRepresentation,根据自己的实际使用场景设置压缩系数,进一步降低图片数据量大小。
4. 拉伸图片
在 >= iOS 5.0 时,UIImage的新方法可以处理图片的拉伸问题:
- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets;
使用过程:
+ (UIImage *)resizableImageName:(NSString *)imageName {
UIImage *oldBackgroundImage = [Utility imageNamedWithFileName:imageName];
CGFloat top = oldBackgroundImage.size.height * 0.5;
CGFloat left = oldBackgroundImage.size.width * 0.5;
CGFloat bottom = oldBackgroundImage.size.height * 0.5;
CGFloat right = oldBackgroundImage.size.width * 0.5;
UIEdgeInsets edgeInsets = UIEdgeInsetsMake(top, left, bottom, right);
UIImageResizingMode mode = UIImageResizingModeStretch;
UIImage *newBackgroundImage = [oldBackgroundImage resizableImageWithCapInsets:edgeInsets resizingMode:mode];
return newBackgroundImage;
}
在 >= iOS 6.0 时,UIImage的新方法可以处理图片的拉伸问题:
- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode;
对比iOS5.0中的方法,只多了一个UIImageResizingMode参数:
UIImageResizingModeStretch:拉伸模式
UIImageResizingModeTile:平铺模式
使用过程:
CGFloat top = 25;
CGFloat bottom = 25;
CGFloat left = 10;
CGFloat right = 10;
UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right);
image = [image resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
参考文章:
https://www.jianshu.com/p/164b8373d17e
https://blog.csdn.net/q199109106q/article/details/8615661
网友评论