Generate bitmap from HTML in Android

后端 未结 5 1786
别跟我提以往
别跟我提以往 2020-11-30 03:25

How do can you generate a bitmap from HTML in Android?

Can the WebView be used for this or is there a better approach (like maybe using the WebVie

5条回答
  •  余生分开走
    2020-11-30 04:01

    A synchronous method that generates a bitmap from an HTML string using a WebView, and can be used within an AsyncTask:

    public Bitmap getBitmap(final WebView w, int containerWidth, int containerHeight, final String baseURL, final String content) {
        final CountDownLatch signal = new CountDownLatch(1);
        final Bitmap b = Bitmap.createBitmap(containerWidth, containerHeight, Bitmap.Config.ARGB_8888);
        final AtomicBoolean ready = new AtomicBoolean(false); 
        w.post(new Runnable() {
    
            @Override
            public void run() {
                w.setWebViewClient(new WebViewClient() {
                    @Override
                    public void onPageFinished(WebView view, String url) {
                        ready.set(true);
                    }
                });
                w.setPictureListener(new PictureListener() {
                    @Override
                    public void onNewPicture(WebView view, Picture picture) {
                        if (ready.get()) {
                            final Canvas c = new Canvas(b);
                            view.draw(c);
                            w.setPictureListener(null);
                            signal.countDown();
                        }
                    }
                });
                w.layout(0, 0, rect.width(), rect.height());
                w.loadDataWithBaseURL(baseURL, content, "text/html", "UTF-8", null);
            }});
        try {
            signal.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return b;
    }
    

    It has some limitations, but it's a start.

提交回复
热议问题