在ios中将html转换为图像

时间:2013-01-03 04:03:32

标签: iphone html objective-c ios ipad

我在我的应用程序中使用多个.html文件并在webview中打开它,我需要将html页面显示为拇指视图,是否可以将html页面转换为图像或任何其他方法来显示将html文件作为预览。如果有人知道,请帮帮我

2 个答案:

答案 0 :(得分:1)

-(void) webViewDidFinishLoad:(UIWebView *)webView { 

UIGraphicsBeginImageContext(CGSizeMake(webView.layer.frame.size.width, webView.layer.frame.size.height));
[webView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();


UIGraphicsBeginImageContext(CGSizeMake(70,100));
[image drawInRect:CGRectMake(0, 0, 70,100)];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

//image is now a 70x100 thumbnail. make sure you include CoreGraphics
}

答案 1 :(得分:0)

WKWebView最近有一种更方便的方法

class WebviewDelegate: NSObject, WKNavigationDelegate {

    var completion: ((UIImage?) -> ())?

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        webView.evaluateJavaScript("document.body.offsetHeight;") { (result, error) in
            if let height = result as? CGFloat {
                let config = WKSnapshotConfiguration()
                config.rect = CGRect(x: 0, y: 0, width: webView.scrollView.contentSize.width, height: height)

                webView.takeSnapshot(with: config) { (image, error) in
                    self.completion?(image)
                }
            }
        }
    }
}