簡體   English   中英

如何將HTML文件(存儲在資產中)轉換為Android中的圖像?

[英]How to convert HTML files (stored in assets) to image in android?

我正在嘗試將存儲為資產的html文件轉換為圖像,以便我可以共享它們。 我嘗試了以下代碼:

Picture picture = webView.capturePicture();
Bitmap b = Bitmap.createBitmap(
        picture.getWidth(), picture.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
picture.draw(c);

FileOutputStream fos = null;
try {
    fos = new FileOutputStream( Environment.getExternalStorageDirectory().toString() +"/temp.jpg");
    if ( fos != null ) {
        b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        Toast.makeText(SyllabusPage_NW.this, "created", Toast.LENGTH_SHORT).show();
        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        Uri screenshotUri = Uri.parse(Environment.getExternalStorageDirectory().toString() + "/temp.jpg");

        sharingIntent.setType("image/jpeg");
        sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
        startActivity(Intent.createChooser(sharingIntent, "Share image using"));
        fos.close();

    }
}
catch( Exception e ) {

    Toast.makeText(SyllabusPage_NW.this, "Error", Toast.LENGTH_SHORT).show();
}

附加了結果,並附加了預期結果。 Web視圖僅捕獲html頁面的第一部分。 我想知道如何捕獲整個html頁面而不只是第一部分?

我得到的圖像

我期望的圖像

對於API Lollipop及更高版本,應啟用緩慢繪制:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    WebView.enableSlowWholeDocumentDraw();
}

然后通過調試檢查圖片的高度是否正確。
如果不是,首先測量Webview,然后進行布局。

webView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
webView.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
webView.buildDrawingCache(true);

Bitmap b = Bitmap.createBitmap(webView.getDrawingCache());
webView.setDrawingCacheEnabled(false);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM