将 HTML 内容转换为图像

sai*_*sif 5 html uiimageview ios swift

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 中,然后我可以轻松地将图像保存在我的应用程序内存中。

Qad*_*ain 3

使用 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)
}
Run Code Online (Sandbox Code Playgroud)

拍摄快照尝试下面的代码

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();
Run Code Online (Sandbox Code Playgroud)