簡體   English   中英

如何在iOS中以編程方式拍攝屏幕截圖?

[英]How to programmatically take a screenshot in iOS?

如何以編程方式拍攝整個屏幕(iPhone)的屏幕截圖並將其保存到iOS中的照片庫? 屏幕上除了標簽和按鈕外什么也沒有。

該按鈕名為“ ScreenshotButton”,需要觸發該按鈕。

  • 我還需要導入QuartzCore嗎?
  • 我到底需要在什么地方將Screenshot函數放在ViewController中?

您需要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);

我定義了static UIImage *screengrab; @implementation之后位於我代碼的頂部。

您應該使用Analyze來檢查泄漏-我在代碼中沒有自己,但是CG代碼似乎總是會創建一些。

以下是用於拍攝視圖快照的類:

#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中以編程方式獲取屏幕截圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM