How to obtain a CGImageRef from the content of an UIView?

倾然丶 夕夏残阳落幕 提交于 2019-12-10 03:00:38

问题


I have an UIView where I was drawing some stuff inside -drawRect:. Now I need a CGImageRef from this graphics context or bitmap of the UIView. Is there an easy way to get that?


回答1:


Like this (typed from memory, so it might not be 100% correct):

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



回答2:


Also make sure that you add

#import <QuartzCore/QuartzCore.h>

to your code




回答3:


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


来源:https://stackoverflow.com/questions/3777497/how-to-obtain-a-cgimageref-from-the-content-of-an-uiview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!