【问题标题】:How to obtain a CGImageRef from the content of an UIView?如何从 UIView 的内容中获取 CGImageRef?
【发布时间】:2010-09-23 10:39:54
【问题描述】:

我有一个 UIView,我在 -drawRect: 中绘制了一些东西。现在我需要来自这个图形上下文或 UIView 位图的 CGImageRef。有没有简单的方法来获得它?

【问题讨论】:

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


    【解决方案1】:

    像这样(从记忆中输入,所以可能不是 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;
    

    【讨论】:

      【解决方案2】:

      还要确保添加

      #import <QuartzCore/QuartzCore.h>

      到你的代码

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-11-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多