将HTML内容转换为UIImage Swift 3

时间:2018-06-08 11:12:07

标签: swift uiimage

有没有人知道如何将HTML内容转换为UIImage我已经引用了这个Like但它对我没什么帮助

在我搜索时,我必须转换NSAttributeString广告中的HTML内容,然后才能将其转换为UIImage,但仍无法正常工作

NSAttributeStringUIImage

static func imageFromString(from text: NSAttributedString) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(text.size(), false, 0.0)
    // draw in context
    text.draw(at: CGPoint(x: 0.0, y: 0.0))
    // transfer image
    let image: UIImage? = UIGraphicsGetImageFromCurrentImageContext()?.withRenderingMode(.alwaysOriginal)
    UIGraphicsEndImageContext()
    return image ?? UIImage()
}

// HTML to NSAttribute String

extension String {
var html2AttributedString: NSAttributedString? {
    do {
        return try NSAttributedString(data: Data(utf8), options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil)
    } catch {
        print("error:", error)
        return nil
    }
}
var html2String: String {
    return html2AttributedString?.string ?? ""
}
}

最后我发现问题Border没有进入Image Refer this link

1 个答案:

答案 0 :(得分:0)

您需要先将文本绘制到视图上。 UILabel.attributedTitle似乎是您的正确选择。