从HTML Android中生成位图 [英] Generate bitmap from HTML in Android
本文介绍了从HTML Android中生成位图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你怎么可以生成HTML从Android中的位图?
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渲染和矩形
是所需的位图的框架。
...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.
这篇关于从HTML Android中生成位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文