捕获屏幕的一部分需要时间

Capture a part of screen takes time

我正在使用此代码来捕获 iPad 屏幕的一部分。

UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGRect rect = CGRectMake(500, 500, 600, 600);
CGImageRef imageRef = CGImageCreateWithImageInRect([viewImage CGImage], 
rect);
UIImage *img = [UIImage imageWithCGImage:imageRef]; 
UIImageWriteToSavedPhotosAlbum(img, nil, nil, nil); 
CGImageRelease(imageRef);

但是与使用代码捕获从 {0,0} 到 {100,100} 的屏幕部分相比,这非常慢

CGRect rect = CGRectMake(0, 0, 200, 200);
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0);
CGContextRef context = UIGraphicsGetCurrentContext();
[yourView.layer renderInContext:context];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

它们之间的区别在于传递给 UIGraphicsBeginImageContext 的矩形大小。我们可以在不将完整的屏幕边界传递给 GraphicContext 的情况下捕获 CGRectMake(500, 500, 600, 600) 吗? 也请写代码。

当然,您可以只捕获视图的一小部分。创建大小为 600x600 的上下文,然后在请求图层渲染之前将上下文的原点转换为 500,500。

CGRect rect = CGRectMake(500, 500, 600, 600);
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, rect.origin.x, rect.origin.y);
[yourView.layer renderInContext:context];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

您可能还想查看 -[UIView drawViewHierarchyInRect:afterScreenUpdates:] 方法。 According to WWDC 2013 Session 226, “Implementing Engaging UI on iOS”drawViewHierarchyInRect:afterScreenUpdates:明显快于renderInContext:。有关速度比较,请参阅幻灯片 41:在他们的示例中,旧方法为 844 毫秒,新方法为 145 毫秒。