在 Android 中从 HTML 生成位图 [英] Generate bitmap from HTML in Android
本文介绍了在 Android 中从 HTML 生成位图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 Android 中从 HTML 生成位图?
How do can you generate a bitmap from HTML in Android?
WebView
可以用于此目的还是有更好的方法(比如直接使用 WebView
渲染引擎)?怎么样?
Can the WebView
be used for this or is there a better approach (like maybe using the WebView
rendering engine directly)? How?
我想实现以下方法...
I would like to implement the following method...
public Bitmap toBitmap(Context context, String html, Rect rect);
...其中 html
是要渲染的 html,rect
是所需位图的框架.
...where html
is the html to render and rect
is the frame of the desired bitmap.
推荐答案
一种使用 WebView 从 HTML 字符串生成位图的同步方法,可以在 AsyncTask 中使用:
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.
这篇关于在 Android 中从 HTML 生成位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文