我有一个UIView,我在-drawRect:中绘制了一些东西。现在,我需要来自此图形上下文或UIView位图的CGImageRef。有一个简单的方法可以做到吗?
类似(从内存中键入,因此可能不是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;
还请确保您添加
#import <QuartzCore/QuartzCore.h>
到您的代码
Swift 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!
}
}