iOS: 把一個(gè) View 轉(zhuǎn)為 Image

引子

最近遇到一個(gè)需求,需要把一個(gè) UIView 轉(zhuǎn)換為一個(gè) UIIamge,這里用到了 UiKit 的上下文,還需要了解 Core Graphics 的一些內(nèi)容,所以總結(jié)一下。

renderInContext

通過 UIGraphicsBeginImageContextWithOptions 這個(gè)方法可以進(jìn)入上下文,UIGraphicsGetCurrentContext 這個(gè)方法可以獲取當(dāng)前的內(nèi)容,通過 UIGraphicsGetImageFromCurrentImageContext 方法可以把當(dāng)前的內(nèi)容轉(zhuǎn)換為 UIImage ,這里用到了 renderInContext 方法。

renderInContext 方法用來渲染當(dāng)前的內(nèi)容。

- (UIImage *)imageWithView:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0f);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshotImage;
}

drawViewHierarchyInRect

iOS7.0 之后引入了一個(gè)新的方法 drawViewHierarchyInRect:afterScreenUpdates:,這個(gè)方法的速度比 renderInContext 快很多,根據(jù)參考的文章里測(cè)試,大約快了 15 倍。

但是 drawViewHierarchyInRect:afterScreenUpdates: 需要當(dāng)前 view 已經(jīng)渲染在界面上,所以不能直接用在 viewDidLoad 中。

- (UIImage *)imageWithView:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, [UIScreen mainScreen].scale);
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];
    UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshotImage;
}

參考

iOS 7 blurring techniques

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容