在一般使用中,會使用 UImage 或者其他 view 加載某個視圖,但是當(dāng)需要進(jìn)行某個相關(guān)操作的時候,必須要使用到 UIImage 對象去操作,這個時候,最方便的方法就是獲取當(dāng)前UIView(所有view父類)的視圖,然后使用代碼去生成、寫入本地磁盤。當(dāng)然了還有使用濾鏡或者截圖直接把需要的范圍拿下來就可以了。具體實現(xiàn)代碼如下:
// 1. 需要使用Method調(diào)用
UIImage *currentImg = [self getImageFromView:self.firstView.drawIV]; //view調(diào)用生成image
[self covertPngOrJpgWithImg:currentImg]; //執(zhí)行寫入保存
//2. UIView轉(zhuǎn)成UIImage
-(UIImage *)getImageFromView:(UIView *)view{
UIGraphicsBeginImageContext(view.bounds.size);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
上述 UIView 生成 UIImage 的方法是使用 renderInCotext 繪制,但是當(dāng)項目中已經(jīng)存在 GPUImage 即 OpenGL ES 類庫時,<font color=#8E236B>上述方法即不可用,因為 renderInContext 和 OpenGL ES 不能同時工作 </font>
下面是在原有基礎(chǔ)上的改進(jìn)方法,同樣在二者同時存在時也可工作。
從新啟用新的截圖方法,使用下面方法渲染view layer圖層
+ (UIImage *)captureImgWhenViewIsGPUImageV:(UIView *)view{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);
CGContextConcatCTM(ctx, [view.layer affineTransform]);
if ([view respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) {//iOS 7+
[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
} else {//iOS 6
[view.layer renderInContext:ctx];
}
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
CGContextRestoreGState(ctx);
UIGraphicsEndImageContext();
return image;
}