iOS屏幕捕获和性能

时间:2013-04-30 09:17:42

标签: ios ipad avfoundation screenshot uigraphicscontext

我正在尝试定期捕获iDevice的屏幕(每秒或当用户触摸屏幕时)。我使用子类UIView执行此操作,其中hitTest方法调用以下内容:

UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
CGRect rect = [keyWindow bounds];
UIGraphicsBeginImageContextWithOptions(rect.size,YES,0.0f);
CGContextRef context = UIGraphicsGetCurrentContext();
[keyWindow.layer renderInContext:context];
UIImage *capturedScreen = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

NSString *pngTitle = [NSString stringWithFormat:@"Documents/Test%d.jpg", imageIdentifier];
NSString  *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:pngTitle];
int tempIdentifier = imageIdentifier+1;
imageIdentifier = tempIdentifier;
[UIImageJPEGRepresentation(capturedScreen, 0.4f) writeToFile:pngPath atomically:YES];

NSError *error;
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
[fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error];

捕获屏幕内容工作正常,但是,它也会导致如此显着的性能下降,这使得我将其嵌入的应用程序几乎无法使用。例如,滑动手势变得如此迟钝,不再在滚动视图上注册。

有没有办法捕获不影响性能的屏幕图像(或者至少不是这么多)?

谢谢!

1 个答案:

答案 0 :(得分:2)

根据您的要求使用GCD:我假设您每getScreen拨打1 second,然后:

-(void)getScreen
{
 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
 dispatch_async(queue, ^{
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    CGRect rect = [keyWindow bounds];
    UIGraphicsBeginImageContextWithOptions(rect.size,YES,0.0f);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [keyWindow.layer renderInContext:context];
    UIImage *capturedScreen = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    NSString *pngTitle = [NSString stringWithFormat:@"Documents/Test%d.jpg", imageIdentifier];
    NSString  *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:pngTitle];
    imageIdentifier = imageIdentifier+1;
    [UIImageJPEGRepresentation(capturedScreen, 0.4f) writeToFile:pngPath atomically:YES];

    NSError *error;
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error];

  dispatch_sync(dispatch_get_main_queue(), ^{
    [self performSelector:@selector(getScreen) withObject:nil afterDelay:1.0];
  });
  });
 }