Generate bitmap from HTML in Android

后端 未结 5 1783
别跟我提以往
别跟我提以往 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:16

    You can use the draw method to let it draw in a Bitmap of your choice. I made an example, don't forget internet and external storage rights of your manifest:

    
    public class MainActivity extends Activity {
        private WebView mWebView;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mWebView = new WebView(this);
            setContentView(mWebView);
            mWebView.loadUrl("http://tea.ch");
        }
        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
          if (keyCode != KeyEvent.KEYCODE_BACK) return super.onKeyDown(keyCode, event);
          Bitmap bm = Bitmap.createBitmap(200, 300, Bitmap.Config.ARGB_8888);
          Canvas c = new Canvas(bm);
          mWebView.draw(c);
          OutputStream stream = null;
          try {
            stream = new FileOutputStream(Environment.getExternalStorageDirectory() +"/teach.png");
            bm.compress(CompressFormat.PNG, 80, stream);
            if (stream != null) stream.close();
          } catch (IOException e) {
          } finally {
            bm.recycle();
          }
    return super.onKeyDown(keyCode, event); } }

提交回复
热议问题