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

问题描述 投票:8回答:3

我有一个UIView,我在-drawRect:中绘制了一些东西。现在,我需要来自此图形上下文或UIView位图的CGImageRef。有一个简单的方法可以做到吗?

iphone cocoa-touch uikit core-graphics quartz-2d
3个回答
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
投票

还请确保您添加

#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!
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.