最近发现百度地图有对公交路线(scrollView)截图的功能。在这里尝试实现对scrollView截图。
对UIScrollView
截图的方法:
- (IBAction) renderScrollViewToImage:(UIScrollView *)scrollView
{
UIImage* image = nil;
UIGraphicsBeginImageContextWithOptions(scrollView.contentSize, 0, 0);
{
CGPoint savedContentOffset = scrollView.contentOffset;
CGRect savedFrame = scrollView.frame;
scrollView.contentOffset = CGPointZero;
scrollView.frame = CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height);
[scrollView.layer renderInContext: UIGraphicsGetCurrentContext()];
image = UIGraphicsGetImageFromCurrentImageContext();
scrollView.contentOffset = savedContentOffset;
scrollView.frame = savedFrame;
}
UIGraphicsEndImageContext();
if (image != nil) {
[UIImagePNGRepresentation(image) writeToFile: @"/Users/tyrad/Desktop/image3.png" atomically: YES];
}
}
对scrollView
截取pdf(最后调用writeToFile:
方法)
- (NSMutableData*)createPDFfromUIScrollView:(UIScrollView*)scrollView{
NSMutableData *pdfData = [NSMutableData data];
NSLog(@"%@",NSStringFromCGSize([scrollView contentSize]));
UIGraphicsBeginPDFContextToData(pdfData, (CGRect){0,0, scrollView.contentSize}, nil);
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, scrollView.contentSize.width,scrollView.contentSize.height), nil);
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
CGRect origSize = scrollView.frame;
CGRect newSize = origSize;
newSize.size = scrollView.contentSize;
[scrollView setFrame:newSize];
[scrollView.layer renderInContext:pdfContext];
[scrollView setFrame:origSize];
UIGraphicsEndPDFContext();
return pdfData;
}
参考
stackoverflow getting-a-screenshot-of-a-uiscrollview
iOS中将UIScrollView转换保存成PDF文件数据
iOS中正确的截屏姿势