Last active
August 29, 2015 14:22
-
-
Save muyexi/fd50198618ef2ef42d9d to your computer and use it in GitHub Desktop.
snapshot webview http://stackoverflow.com/a/6950666/2122622
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (UIImage *)snapshot { | |
int webViewHeight = [self stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight;"].floatValue; | |
CGFloat pageHeight = self.frame.size.height; | |
int pageCount = webViewHeight / pageHeight; | |
if ((webViewHeight % pageCount) > 0) { | |
pageCount++; | |
} | |
for (int i = 0; i < pageCount; i++) { | |
UIImage *image; | |
@autoreleasepool { | |
UIGraphicsBeginImageContextWithOptions(self.frame.size, YES, 2.0); | |
[self.layer renderInContext:UIGraphicsGetCurrentContext()]; | |
image = UIGraphicsGetImageFromCurrentImageContext(); | |
UIGraphicsEndImageContext(); | |
NSData *imageData = UIImageJPEGRepresentation(image, 0.0); | |
NSString *imageName = [NSString stringWithFormat:@"image%i.jpg", i]; | |
NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:imageName]; | |
[imageData writeToFile:filePath atomically:YES]; | |
CGPoint nextPoint = CGPointMake(0, pageHeight * (i + 1)); | |
[self.scrollView setContentOffset:nextPoint]; | |
image = nil; | |
imageData = nil; | |
} | |
} | |
UIImage *completeImage; | |
@autoreleasepool { | |
CGSize completeImageSize = CGSizeMake(self.scrollView.contentSize.width * 2, 40000); | |
UIGraphicsBeginImageContextWithOptions(completeImageSize, YES, 1.0); | |
for (int i = 0; i < pageCount; i++) { | |
NSString *imageName = [NSString stringWithFormat:@"image%i.jpg", i]; | |
NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:imageName]; | |
UIImage *pageImage = [UIImage imageWithContentsOfFile:filePath]; | |
CGFloat pageImageHeight = pageHeight * 2; | |
CGPoint imagePoint = CGPointMake(0, pageImageHeight * i); | |
[pageImage drawAtPoint:imagePoint]; | |
pageImage = nil; | |
} | |
completeImage = UIGraphicsGetImageFromCurrentImageContext(); | |
UIGraphicsEndImageContext(); | |
} | |
return completeImage; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment