简体   繁体   English

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

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

I have an UIView where I was drawing some stuff inside -drawRect:.我有一个 UIView,我在 -drawRect: 里面画了一些东西。 Now I need a CGImageRef from this graphics context or bitmap of the UIView.现在我需要一个来自 UIView 的图形上下文或位图的 CGImageRef。 Is there an easy way to get that?有没有简单的方法来获得它?

Like this (typed from memory, so it might not be 100% correct):像这样(从内存中输入,所以它可能不是 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;

Swift 5斯威夫特 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!
    }
}

Also make sure that you add还要确保您添加

#import <QuartzCore/QuartzCore.h>

to your code到你的代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM