【问题标题】:How to programmatically take a screenshot in iOS?如何以编程方式在 iOS 中截取屏幕截图?
【发布时间】:2016-03-18 18:27:08
【问题描述】:

如何以编程方式截取整个屏幕 (iPhone) 的屏幕截图并将其保存到 iOS 中的照片库?屏幕上除了一些标签和一个按钮之外什么都没有。

需要触发此按钮的按钮名为“ScreenshotButton”。

  • 我还需要导入 QuartzCore 吗?
  • 我需要将屏幕截图功能放置在 ViewController 中的什么位置?

【问题讨论】:

    标签: ios screenshot


    【解决方案1】:

    您需要 CoreGraphics。这是我在按钮的 IBAction 中使用的代码:

    CGRect rect = [[UIScreen mainScreen] bounds];
    
    CGSize imageSize = rect.size;
    
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSaveGState(ctx);
    CGContextConcatCTM(ctx, [self.view.layer affineTransform]);
    
    if ([self.view respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) { // iOS 7+
        [self.view drawViewHierarchyInRect:self.view.bounds afterScreenUpdates:YES];
    } else { // iOS 6
        [self.view.layer renderInContext:ctx];
    }
    screengrab = UIGraphicsGetImageFromCurrentImageContext();
    
    CGContextRestoreGState(ctx);
    UIGraphicsEndImageContext();
    
    UIImageWriteToSavedPhotosAlbum(screengrab, nil, nil, nil);
    

    我在@implementation 之后的代码顶部定义了static UIImage *screengrab;。

    您应该使用分析来检查泄漏——我在这段代码中没有任何我自己,但 CG 代码似乎总是会创建一些。

    【讨论】:

      【解决方案2】:

      以下是用于拍摄视图快照的类:

      #import "ScreenSnapshot.h"
      #import <QuartzCore/QuartzCore.h>
      
      @implementation ScreenSnapshot
      
      static NSUInteger imgNumber;
      
      + (void)initialize { imgNumber = 0; }
      
      + (void)saveScreenSnapshot:(UIView *)view {
      
          UIImage * img = [self screenSnapshotOf:view];
          NSData * data = UIImagePNGRepresentation(img);
          imgNumber += 1;
      
          NSString * fullPath = [NSString stringWithFormat:@"%@/Documents/img_%ld.png",NSHomeDirectory(),imgNumber];
      
          [data writeToFile:fullPath
                 atomically:YES];
      }
      
      + (UIImage *)screenSnapshotOf:(UIView *)view {
      
          UIGraphicsBeginImageContext(view.frame.size);
          CGContextRef context = UIGraphicsGetCurrentContext();
      
          [view.layer renderInContext:context];
      
          UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
          UIGraphicsEndImageContext();
      
          return img;
      }
      
      @end
      

      将此代码原样复制到一个名为“ScreenSnapshot”的新类中。

      在你的“ScreenshotButton”动作中,写:

      [ScreenSnapshot saveScreenSnapshot:self.view];
      

      ...在导入“ScreenSnapshot.h”之后。

      您可以替换我的代码中用于存储图像的位置,并且您将能够以编程方式在 iOS 中截取屏幕截图。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-13
        • 2023-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-06
        • 1970-01-01
        相关资源
        最近更新 更多