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

8

我有一个UIView,在其中使用-drawRect:方法绘制了一些内容。现在,我需要从这个图形上下文或UIView的位图中获取CGImageRef。有没有简单的方法可以实现这一点?

3个回答

11

像这样(从记忆中打出来,可能不完全正确):

// 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;

0

还要确保在你的代码中添加

#import <QuartzCore/QuartzCore.h>

这样做也是必要的


0

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接