【发布时间】:2010-09-23 10:39:54
【问题描述】:
我有一个 UIView,我在 -drawRect: 中绘制了一些东西。现在我需要来自这个图形上下文或 UIView 位图的 CGImageRef。有没有简单的方法来获得它?
【问题讨论】:
标签: iphone cocoa-touch uikit core-graphics quartz-2d
我有一个 UIView,我在 -drawRect: 中绘制了一些东西。现在我需要来自这个图形上下文或 UIView 位图的 CGImageRef。有没有简单的方法来获得它?
【问题讨论】:
标签: iphone cocoa-touch uikit core-graphics quartz-2d
像这样(从记忆中输入,所以可能不是 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>
到你的代码
【讨论】:
斯威夫特 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!
}
}
【讨论】: