[英]How to obtain a CGImageRef from the content of an UIView?
我有一个 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;
斯威夫特 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!
}
}
还要确保您添加
#import <QuartzCore/QuartzCore.h>
到你的代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.