嘿,我正在尝试通过以下方式将 webview 绘制到位图:
CustomWebView webView = (CustomWebView) findViewById(R.id.chart_webview_renderer);
String capturePathString = Environment.getExternalStorageDirectory().getPath() + "/temp/ms_" + System.currentTimeMillis() + ".png";
Bitmap bm = Bitmap.createBitmap(webView.getMeasuredWidth(), webView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas bigcanvas = new Canvas(bm);
Paint paint = new Paint();
int iHeight = bm.getHeight();
bigcanvas.drawBitmap(bm, 0, iHeight, paint);
webView.draw(bigcanvas);
if (bm != null) {
try {
OutputStream fOut = null;
File file = new File(capturePathString);
fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 50, fOut);
fOut.close();
fOut.flush();
bm.recycle();
} catch (Exception e) {
e.printStackTrace();
}
}
这在我们可用于此处测试的平板电脑(Galaxy Tab 2 和 3)上运行良好。但会在 Sony Xperia Z 和 Samsung Galaxy S2 上生成正确大小的白色位图。
它试图绘制到位图的网页只包含一个 HTML5 Canvas ,当我也向其中添加普通 HTML 时,它会很好地将那个 HTML 绘制到位图。
webview 被设置为在所有 View 后面不可见,尽管我已经尝试将其设置为可见并位于所有 View 之上,但没有产生不同的结果。
最佳答案
我用原来的方法没能解决这个问题。所以我在 html 中添加了以下 javascript 修复程序:https://code.google.com/p/todataurl-png-js/允许使用
canvas.toDataUrl()
返回一个 Base64 编码的 PNG 图片。然后我用了
WebView.addJavascriptInterface
允许 javascript 将 base64 编码的图像发送到 java,然后将其保存在设备上。
我所做的粗略示例如下:
// After initializing the webview:
JavaScriptInterface jsInterface = new JavaScriptInterface();
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(jsInterface, "android");
// The class used as javascript interface for saving the image to a file
public class JavaScriptInterface {
@JavascriptInterface
public void canvasToImage(String base64ImageData){
String capturePathString = Environment.getExternalStorageDirectory().getPath() + "/temp/ms_" + System.currentTimeMillis() + ".png";
try{
File file = new File(capturePathString);
file.getParentFile().mkdirs();
FileOutputStream fos = new FileOutputStream(file);
byte[] decodedString = android.util.Base64.decode(base64ImageData, android.util.Base64.DEFAULT);
fos.write(decodedString);
fos.flush();
fos.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
// In the javascript it looks something like this
function canvasToImage(){
var dataUrl = canvas.toDataURL();
window.android.canvasToImage(dataUrl.replace("data:image/png;base64,", ""));
}
它不像我希望的那样干净,但它现在适用于这里的所有设备!
关于android - WebView.draw(android.graphics.Canvas) 不会将 HTML5 Canvas 绘制到 android.graphics.Canvas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22296768/