如何从UIView的内容中获取CGImageRef?

时间:2010-09-23 10:39:55

标签: iphone cocoa-touch uikit core-graphics quartz-2d

我有一个UIView,我正在绘制一些东西--drawRect:。现在我需要来自这个图形上下文或UIView位图的CGImageRef。是否有一种简单的方法可以实现这一目标?

3 个答案:

答案 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!
    }
}