【问题标题】:Need to capture UIView into a UIImage, including all subviews需要将UIView捕获到一个UIImage中,包括所有的子视图
【发布时间】:2010-06-27 23:48:44
【问题描述】:

我需要将 UIView 及其所有子视图捕获到 UIImage 中。问题是视图的一部分不在屏幕上,所以我不能使用屏幕捕获功能,当我尝试使用 UIGraphicsGetImageFromCurrentImageContext() 函数时,它似乎也没有捕获子视图。它是否应该捕获子视图而我只是做错了什么?如果没有,有没有其他方法可以做到这一点?

【问题讨论】:

  • 我猜因为每个UIView 都是基于层的调用-[CALayer drawInContext:viewContext] 可能会有所帮助。

标签: iphone uiview uiimage


【解决方案1】:

这是正确的方法:

+ (UIImage *) imageWithView:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, [[UIScreen mainScreen] scale]); 
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

此方法是 UIImage 类的扩展方法,它还将负责使图像在任何未来的高分辨率设备上看起来都很好。

【讨论】:

    【解决方案2】:

    你是说

    UIGraphicsBeginImageContext(view.bounds.size);
    [view.layer drawInContext:UIGraphicsGetCurrentContext()];
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    不工作?我很确定它应该...

    【讨论】:

      【解决方案3】:

      Swift 4+ 版本:

      func getImage(from view:UIView) -> UIImage? {
      
          defer { UIGraphicsEndImageContext() }
          UIGraphicsBeginImageContextWithOptions(view.frame.size, true, UIScreen.main.scale)
          guard let context =  UIGraphicsGetCurrentContext() else { return nil }
          view.layer.render(in: context)
          return UIGraphicsGetImageFromCurrentImageContext()   
      
      }
      

      【讨论】:

        【解决方案4】:

        这是一个 Swift 2.x 版本,如果您首先创建一个 UIViews 数组以进行扁平化,那么它应该可以工作:

        // Flattens <allViews> into single UIImage
        func flattenViews(allViews: [UIView]) -> UIImage? {
            // Return nil if <allViews> empty
            if (allViews.isEmpty) {
                return nil
            }
        
            // If here, compose image out of views in <allViews>
            // Create graphics context
            UIGraphicsBeginImageContextWithOptions(UIScreen.mainScreen().bounds.size, false, UIScreen.mainScreen().scale)
            let context = UIGraphicsGetCurrentContext()
            CGContextSetInterpolationQuality(context, CGInterpolationQuality.High)
        
            // Draw each view into context
            for curView in allViews {
                curView.drawViewHierarchyInRect(curView.frame, afterScreenUpdates: false)
            }
        
            // Extract image & end context
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
        
            // Return image
            return image
        }
        

        【讨论】:

          猜你喜欢
          • 2012-02-16
          • 1970-01-01
          • 2019-05-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-11-20
          相关资源
          最近更新 更多