【问题标题】:make a UIView with added subviews into a single image?将添加了子视图的 UIView 制作成单个图像?
【发布时间】:2012-06-21 20:50:20
【问题描述】:

我有一个添加了子视图的视图。我想将具有许多子视图的视图转换为单个图像或视图。

这怎么可能?
谢谢

【问题讨论】:

    标签: ios uiview


    【解决方案1】:

    在 iOS7 上,您可以使用新的 [UIView snapshotViewAfterScreenUpdates:] 方法。

    为了支持较旧的操作系统,您可以使用 Core Graphics 将任何视图渲染到 UIImage 中。我在 UIView 上使用这个类别来拍摄快照:

    UView+Snapshot.h:

    #import <UIKit/UIKit.h>
    
    @interface UIView (Snapshot)
    - (UIImage *)snapshotImage;
    @end
    

    UView+Snapshot.m:

    #import "UIView+Snapshot.h"
    #import <QuartzCore/QuartzCore.h>
    
    @implementation UIView (Snapshot)
    
    - (UIImage *)snapshotImage
    {
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0.0);
        [self.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return resultingImage;
    }
    
    @end
    

    它需要 QuartzCore 框架,因此请确保将其添加到您的项目中。

    要使用它,请导入标题并:

    UIImage *snapshot = [interestingView snapshotImage];
    

    【讨论】:

    • Vytis,除了UIImage *snapshot = [interestingView snapshotImage]; Xcode 抱怨:Use of undeclared identifier interestingView’ 之外,这里的一切都有意义。你到底是怎么声明的?
    • interestingView 是您要为其拍摄快照图像的视图。因此,例如,如果您想拍摄视图控制器视图的快照,您的 UIViewController 代码中的某处将有 UIImage *snapshot = [self.view snapshotImage];
    【解决方案2】:

    确实有可能,使用 Core Graphics 的渲染函数将视图渲染到上下文中,然后使用该上下文的内容初始化图像。请参阅this question 的答案以获得良好的技术。

    【讨论】:

      【解决方案3】:

      Swift 5,调用方便

      extension UIView {
          var asImg: UIImage? {
              let renderer = UIGraphicsImageRenderer(bounds: bounds)
              return renderer.image { rendererContext in
                  layer.render(in: rendererContext.cgContext)
              }
          }
      }
      

      【讨论】:

        【解决方案4】:

        这是 Vytis 示例的 swift 2.x 版本

        extension UIView {
        
            func snapshotImage() -> UIImage {
                UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0.0)
                self.layer.renderInContext(UIGraphicsGetCurrentContext()!)
                let resultingImage = UIGraphicsGetImageFromCurrentImageContext()
                UIGraphicsEndImageContext()
                return resultingImage
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-05-12
          相关资源
          最近更新 更多