如何以编程方式在iOS中截取屏幕截图?

时间:2015-12-13 02:15:35

标签: ios screenshot

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

按钮名为" ScreenshotButton"需要触发这个。

  • 我还需要导入QuartzCore吗?
  • 我究竟需要将截屏函数放在ViewController中?

2 个答案:

答案 0 :(得分:1)

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

class EnhancedFile(file):
    def __init__(self, *args, **keyws):
        file.__init__(self, *args, **keyws)

    def __len__(self):
        return int(os.fstat(self.fileno())[6])


def b2_upload_file(self, file_name, file_content):
    file_contents = file_content.read()
    tup = tempfile.mkstemp() # make a tmp file
    f = os.fdopen(tup[0], 'w') # open the tmp file for writing
    f.write(file_contents) # write the tmp file
    f.close()

    ### return the path of the file
    filepath = tup[1] # get the filepath
    data_file = EnhancedFile(filepath, 'rb')

    sha1_of_file_data = hashlib.sha1(file_contents).hexdigest()
    content_type = getattr(file_contents, 'content_type',mimetypes.guess_type(file_name)[0] or self.key_class.DefaultContentType)
    headers = {
        'Authorization' : self.upload_auth_token,
        'X-Bz-File-Name' :  file_name,
        'Content-Type' : content_type,
        'X-Bz-Content-Sha1' : sha1_of_file_data
    }

    request = urllib2.Request(self.upload_url, data_file, headers)
    response = urllib2.urlopen(request)
    response_data = json.loads(response.read())
    response.close()
    file_id = response_data['fileId']
    return file_id

def _save(self, name, content):
    self.b2_authorize_account()
    self.b2_get_upload_url()
    file_id = self.b2_upload_file(name, content)
    return file_id

我在@implementation后面的代码顶部定义了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);

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

答案 1 :(得分:0)

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

#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

将此代码复制到名为&#39; ScreenSnapshot&#39;的新类中。

在你的&#34; ScreenshotButton&#34;动作,写&#39; [ScreenSnapshot saveScreenSnapshot:self.view];&#39;导入&#34; ScreenSnapshot.h&#34;。

之后

您可以替换我的代码中使用的位置来存储图像......这应该回答您的问题。