我有一个UIView,在其中使用-drawRect:方法绘制了一些内容。现在,我需要从这个图形上下文或UIView的位图中获取CGImageRef。有没有简单的方法可以实现这一点?
我有一个UIView,在其中使用-drawRect:方法绘制了一些内容。现在,我需要从这个图形上下文或UIView的位图中获取CGImageRef。有没有简单的方法可以实现这一点?
像这样(从记忆中打出来,可能不完全正确):
// 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!
}
}