我正在尝试定期捕获 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/