【问题标题】:Convert HTML Content to image将 HTML 内容转换为图像
【发布时间】:2017-09-21 19:51:53
【问题描述】:

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

【问题讨论】:

  • UIImageView请解释...
  • Swift 特有的 UIImageView。
  • 您想将该内容放入 UIImageView 吗?将它放在 UITextView 或 UILabel 中似乎更有逻辑......
  • 是的。实际上我想将 HTML 内容转换为 Image 并将其保存在 FileManager 中。
  • 标签不支持要渲染的图像。

标签: html ios swift uiimageview


【解决方案1】:

使用 label/UITextView 试试这个解决方案

为您的标签设置 html 文本。

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)
}

拍摄快照试试下面的代码

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();

【讨论】:

  • 搞定了。但是使用“UITextView”而不是“LABEL”,因为 labelview 没有渲染图像并且背景也发生了变化。
【解决方案2】:

对此我不确定,但您可以这样做,例如在 UIWebView 中渲染 HTML。然后通过代码截取屏幕截图。

【讨论】:

  • 我已经这样做了。但是使用这种方法图像质量很差。
  • 如何在 UITextView 中将其显示为 NSAttributedstring 然后截图。 (正如上面 Qadir 所说)
猜你喜欢
  • 2012-06-19
  • 1970-01-01
  • 1970-01-01
  • 2013-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-02
  • 2010-10-14
相关资源
最近更新 更多