如何从UIView的内容中获取CGImageRef?

ope*_*rog 8 iphone cocoa-touch core-graphics uikit quartz-2d

我有一个UIView,我正在绘制一些东西--drawRect:.现在我需要来自这个图形上下文或UIView位图的CGImageRef.有一个简单的方法来获得它吗?

Ole*_*ann 12

像这样(从内存中输入,所以它可能不是100%正确):

// Get a UIImage from the view's contents
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, view.contentScaleFactor);
CGContextRef context = UIGraphicsGetCurrentContext();
[view.layer renderInContext:context];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

// Convert UIImage to CGImage
CGImageRef cgImage = image.CGImage;
Run Code Online (Sandbox Code Playgroud)