UIView生成UIImage對象

在一般使用中,會使用 UImage 或者其他 view 加載某個視圖,但是當需要進行某個相關操作的時候,必須要使用到 UIImage 對象去操作,這個時候,最方便的方法就是獲取當前UIView(所有view父類)的視圖,然后使用代碼去生成、寫入本地磁盤。當然了還有使用濾鏡或者截圖直接把需要的范圍拿下來就可以了。具體實現代碼如下:

// 1. 需要使用Method調用
        UIImage *currentImg = [self getImageFromView:self.firstView.drawIV]; //view調用生成image           
       [self covertPngOrJpgWithImg:currentImg]; //執行寫入保存

//2. UIView轉成UIImage
-(UIImage *)getImageFromView:(UIView *)view{
    UIGraphicsBeginImageContext(view.bounds.size);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}


上述 UIView 生成 UIImage 的方法是使用 renderInCotext 繪制,但是當項目中已經存在 GPUImageOpenGL ES 類庫時,<font color=#8E236B>上述方法即不可用,因為 renderInContextOpenGL ES 不能同時工作 </font>
下面是在原有基礎上的改進方法,同樣在二者同時存在時也可工作。

從新啟用新的截圖方法,使用下面方法渲染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;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。