我有一个UIView,我正在绘制一些东西--drawRect:。现在我需要来自这个图形上下文或UIView位图的CGImageRef。是否有一种简单的方法可以实现这一目标?
答案 0 :(得分: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;
答案 1 :(得分:1)
还要确保添加
#import <QuartzCore/QuartzCore.h>
代码
答案 2 :(得分:0)
快速5
extension UIView {
var cgImage: CGImage? {
guard bounds.size.width > 0 && bounds.size.height > 0 else {return nil}
UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, contentScaleFactor)
layer.render(in: UIGraphicsGetCurrentContext()!)
defer {UIGraphicsEndImageContext()}
return UIGraphicsGetImageFromCurrentImageContext()!.cgImage!
}
}