将HTML内容转换为图像

HTML内容示例: This is HTML Content.

This is BOLD text
This is ITALIC text

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

使用label / UITextView尝试此解决方案

将html文本设置为您的标签。

 do { let attrStr = try NSAttributedString( data: "text".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(); 

我不确定这一点,但你可以这样做,比如在UIWebView中渲染HTML。 然后通过代码截取屏幕截图。