在Objective C中实现屏幕截图可以使用以下代码:
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, YES, 0.0);
[self.view drawViewHierarchyInRect:self.view.bounds afterScreenUpdates:YES];
UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
该代码使用UIKit库中的UIGraphicsBeginImageContextWithOptions方法创建上下文对象,并使用UIView的drawViewHierarchyInRect方法在该上下文对象中绘制当前view的快照,最后使用UIGraphicsGetImageFromCurrentImageContext方法获取该快照。
如果你需要捕捉整个屏幕,而不只是当前的view,可以使用以下代码:
CGRect screenRect = [[UIScreen mainScreen] bounds];
UIGraphicsBeginImageContextWithOptions(screenRect.size, NO, 0.0);
CGContextRef context = UIGraphicsGetCurrentContext();
for (UIWindow *window in [[UIApplication sharedApplication] windows]) {
CGContextSaveGState(context);
CGContextTranslateCTM(context, window.center.x, window.center.y);
CGContextConcatCTM(context, window.transform);
CGContextTranslateCTM(context, -window.bounds.size.width * window.layer.anchorPoint.x, -window.bounds.size.height * window.layer.anchorPoint.y);
[window.layer renderInContext:context];
CGContextRestoreGState(context);
}
UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
该代码使用UIScreen中的bounds属性来获取屏幕大小,使用UIGraphicsBeginImageContextWithOptions方法创建上下文对象。由于我们需要获取整个屏幕的快照,因此需要遍历所有的UIWindow,并且将它们渲染到上下文对象中。最后使用UIGraphicsGetImageFromCurrentImageContext方法获取该快照。