我正在尝试做一个简单的任务;将 UIWebView 的内容转换为 UIImage 并将其保存到手机的文档目录中,但是每次运行以下代码时,我都会收到一堆类似的错误:
UIGraphicsBeginImageContext(rect.size);
[self.webView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
创建以下错误:
Jun 10 20:06:18 <Error>: CGContextSaveGState: invalid context 0x0
Jun 10 20:06:18 <Error>: CGContextSetAlpha: invalid context 0x0
Jun 10 20:06:18 <Error>: CGContextSaveGState: invalid context 0x0
Jun 10 20:06:18 <Error>: CGContextSetFillColorWithColor: invalid context 0x0
Jun 10 20:06:18 <Error>: CGContextAddRect: invalid context 0x0
Jun 10 20:06:18 <Error>: CGContextDrawPath: invalid context 0x0
我做了一些研究,发现这是由于上面的代码不在 -(void)drawRect:(CGRect)rect 方法中,但是,在 UIWebView 初始化后如何调用它,或者我不调用它手动?
这是我用来创建 HTML 并将其加载到 WebView 中的代码:
-(void)saveHTMLDocument {
NSMutableString *htmlDocumentToSave = [[NSMutableString alloc] initWithString:@"<html><body>"];
[htmlDocumentToSave appendString:@"<table border=""1""><tr><th>Snag Number</th><th>Snag Photo</th><th>Snag Description</th><th>Date Taken</th>"];
for (int i = 0; i < self.fetchedResultsController.fetchedObjects.count; i++) {
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation([self.photoArray objectAtIndex:i])];
NSString *base64String = [imageData base64EncodedString];
Snag *snag = [self.fetchedResultsController.fetchedObjects objectAtIndex:i];
NSString *tableString = [NSString stringWithFormat:@"<tr><td>%i</td><td><p><b><img src='data:image/png;base64,%@'></b></p></td><td>%@</td><td>%@</td></tr>", i+1, base64String, snag.snagDescription, snag.dateTaken];
[htmlDocumentToSave appendString:tableString];
}
[htmlDocumentToSave appendString:@"</table></body></html>"];
//Save the HTMl document that will be attached.
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *htmlPath = [documentsPath stringByAppendingPathComponent:@"test"];
[htmlDocumentToSave writeToFile:htmlPath atomically:NO encoding:NSUTF8StringEncoding error:nil];
self.htmlData = [NSData dataWithContentsOfFile:htmlPath];
//Generate the UIWebView and load the HTML into it
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"];
NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile];
self.webView = [[UIWebView alloc] init];
[self.webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@""]];
NSString *string = [self.webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('html')[0].innerHTML"];
NSLog(@"Check if WebView has loaded %@", string);
}
-(void)drawRect:(CGRect)rect {
UIGraphicsBeginImageContext(rect.size);
[self.webView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}