上一篇文章我们说到TableView和CollectionView的滚动功能时候提高截图,那么现在分享一下截取TableView和CollectionView的代码:
#pragma mark ==========截图==========
- (UIImage *)snapshotScreen{
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]){
UIGraphicsBeginImageContextWithOptions(self.collectionView.contentSize, NO, [UIScreen mainScreen].scale);
} else {
UIGraphicsBeginImageContext(self.collectionView.contentSize);
}
//先保存原来frame 和 偏移量
CGPoint savedContentOffset = self.collectionView.contentOffset;
CGRect savedFrame = self.collectionView.frame;
CGSize contentSize = self.collectionView.contentSize;
CGRect oldBounds = self.collectionView.layer.bounds;
if(@available(iOS 13, *)){
//iOS 13 系统截屏需要改变tableview 的bounds
[self.collectionView.layer setBounds:CGRectMake(oldBounds.origin.x, oldBounds.origin.y, contentSize.width, contentSize.height)];
}
//偏移量归零
self.collectionView.contentOffset = CGPointZero;
//frame变为contentSize
self.collectionView.frame = CGRectMake(0, 0, self.collectionView.contentSize.width, self.collectionView.contentSize.height);
//截图
[self.collectionView.layer renderInContext:UIGraphicsGetCurrentContext()];
if(@available(iOS 13,*)){
[self.collectionView.layer setBounds:oldBounds];
}
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//还原frame 和 偏移量
self.collectionView.contentOffset = savedContentOffset;
self.collectionView.frame = savedFrame;
return image;
}
TableView的截图代码也是一样的,就改一下就好了。
END.