
引子
最近遇到一個(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;
}