objective-c - 将 HTML 文档转换为 cocoa 中的图像

标签 objective-c

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

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

我在网上找不到任何资源或示例,它们对我的上述查询提供了某种帮助。如果有人可以分享他的智慧,我将如何实现这一点,我将不胜感激。

提前致谢..

最佳答案

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

以下是在不显示页面的情况下制作页面缩略图的方法:

// 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]];

然后在你的委托(delegate)中实现它:

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

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

thumbnailImageView.image = [UIImage imageWithData:thumbnailData];

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

关于objective-c - 将 HTML 文档转换为 cocoa 中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6136206/

相关文章:

objective-c - 将ansi c导入iphone项目后代码运行非常缓慢

objective-c - Xcode 5——测试目标没有完成

ios - 从 AppDelegate 向 ViewController 发送通知

objective-c - 使用 NIPagingScrollView 使 3 个 View 可见?

用于检测具有预定义接近 UDID 的信标的 iOS 范围

ios - 如何创建居中对齐的 Nsstring

objective-c - Objective C 泛型 - 条件编译

objective-c - UILabel 使用剪辑渲染部分字符

objective-c - 时间分析器工具未显示 objective-c 函数

ios - Xcode std::__1::basic_ostream undefined symbol