iOS 屏幕捕获和性能

标签 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];

捕获屏幕内容工作正常,但是,它也会导致性能急剧下降,以至于我嵌入它的应用程序几乎无法使用。它变得如此缓慢,以至于滑动手势,例如,不再在 ScrollView 上注册。

有没有一种方法可以捕获不影响性能(或至少不会影响性能)的屏幕图像?

谢谢!

最佳答案

根据您的要求使用 GCD:我假设您每 1 秒 调用一次 getScreen 然后:

-(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];
  });
  });
 }

关于iOS 屏幕捕获和性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16296306/

相关文章:

ipad - 带有许多按钮的 Xcode iPad UIActionSheet 无法正确显示 iOS7

iphone - 文本文件问题

swift - 在拍摄照片之前切换 AVCaptureSessionPreset

ios - H.264 .mov 文件上的一帧后 AVAssetReader 失败

ios - 使用串行蓝牙连接设备时出现问题

ios - 纹理图集 - 矩阵还是坐标?

iphone - 如何手动符号化 iOS 崩溃以查看崩溃日志

ios - FireBase iOS 消息传递,无法获取 APNS token

iphone - RestKit集成问题 "No Such File Or directory"

swift - 有没有办法将 CMSampleBuffer 转换为 CVImageBuffer?