将HTML内容转换为图像 [英] Convert HTML Content to image

查看:153
本文介绍了将HTML内容转换为图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTML内容示例:这是HTML内容。< div>这是< b> BOLD< / b> text< / div>< div>这是< i> ITALIC< / i> text< / div>
这是我要渲染的HTML内容,并将其放在UIImageView中,然后保存此图像。
我试图首先渲染HTML内容并生成PDF然后将该PDF转换为图像,但该图像的结果非常糟糕。这就是为什么我找到一些渲染我的HTML内容并添加到UIImageVIew中的东西,而不是我会轻松地将该图像保存在我的应用程序内存中。

HTML Content Example : This is HTML Content.<div>This is <b>BOLD</b> text </div><div>This is <i> ITALIC </i> text</div> This is the HTML content which I want to render and place it in a UIImageView and then save this image. I tried to first render that HTML content and generated a PDF and then convert that PDF into Image but that image is of very bad result. So that's why I am finding some thing that render my HTML content and add into UIImageVIew and than I will easily save that image inside my application memory.

推荐答案

使用label / UITextView

Try this solution using label/UITextView

将html文本设置为标签,尝试此解决方案。

set html text to your label.

do {
let attrStr = try NSAttributedString(
    data: "<b><i>text</i></b>".data(using: String.Encoding.unicode, allowLossyConversion: true)!,
    options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
    documentAttributes: nil)
yourLabel.attributedText = attrStr
} catch let error {
  print(error)
}

拍摄快照尝试下面的代码

to take snapshot try below code

UIGraphicsBeginImageContextWithOptions(yourLabel.bounds.size, 
false, 0);
yourLabel.drawViewHierarchyInRect(yourLabel.bounds, afterScreenUpdates: true)
let copied = UIGraphicsGetImageFromCurrentImageContext(); // You have to save this content in your internal memory
yourImageView.image = copied // To Preview that Image in your ImageView
UIGraphicsEndImageContext();

这篇关于将HTML内容转换为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆