将HTML文档转换为可可中的图像

Vin*_*ain 5 objective-c

是否可以将HTML页面转换为可可中的图像?

实际上我已经在HTML中创建了完整的视图,现在我想将整个html预览转换为图像(任何jpeg或png等).

我在网上找不到任何资源或样本,这为我的上述查询提供了一些帮助.如果有人能够分享他如何实现这一目标,我将非常感激.

提前致谢..

Art*_*are 7

首先,我要感谢塞尔吉奥......他的回答让我开始,但我想我会分享一些我没有发现的明显的代码,我必须写它才能使它工作:

以下是如何为页面制作缩略图而不显示它:

// Your width and height can be whatever you like, but if you want this to render
// off screen, you need an x and y bigger than the superview's width and height
UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectMake(largerScreenDimension, largerScreenDimension, largerScreenDimension, largerScreenDimension)];
[self.view addSubview:webView]; // UIWebViews without an assigned superview don't load ever.
webView.delegate = self; // or whoever you have implement UIWebViewDelegate
webView.scalesToFit = YES; // This zooms the page appropriately to fill the entire thumbnail.
[webView loadRequest:[NSURLRequest requestWithURL:url]];
Run Code Online (Sandbox Code Playgroud)

然后在你的委托中实现这个:

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    UIGraphicsBeginImageContext(webView.bounds.size);
    [webView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *webViewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData *thumbnailData = UIImagePNGRepresentation(webViewImage);
    [webView removeFromSuperview];
}
Run Code Online (Sandbox Code Playgroud)

最后,要显示此缩略图,您需要以下内容:

thumbnailImageView.image = [UIImage imageWithData:thumbnailData];
Run Code Online (Sandbox Code Playgroud)

作为奖励,我要提一下,我想一次生成多个缩略图.我发现使用objc_setAssociatedObject()并且objc_getAssociatedObject()非常有助于跟踪哪个webView正在加载哪个缩略图.但是,详细说明它是如何工作的,超出了这个问题的范围.