Capture entire content of EditText into a picture

空扰寡人 提交于 2019-12-06 04:19:10

After searching for another 24 hours for a solution I ran into this solution for a Webview. The trick is

  1. generate another View to hold the content to avoid the marker for EditText on the lower edge of view which will be also printed into the picture
  2. copy the Bitmap to avoid problems with software renderer after destroyDrawingCache() when trying to use Bitmap.compress().

Here is the code:

EditText editText = (EditText) findViewById(R.id.editText);
TextView textView = new TextView(this.getApplicationContext());

textView.setTypeface(editText.getTypeface());
textView.setText(editText.getText());
textView.measure(
    View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),
    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
textView.layout(0, 0, textView.getMeasuredWidth(), textView.getMeasuredHeight());
textView.setDrawingCacheEnabled(true);
textView.buildDrawingCache();

Bitmap b = textView.getDrawingCache().copy(Bitmap.Config.ARGB_8888, false);
textView.destroyDrawingCache();

try{
    String path = Environment.getExternalStorageDirectory().toString() + "/picture.png";
    OutputStream outputStream = new FileOutputStream(new File(path));
    b.compress(Bitmap.CompressFormat.PNG, 0, outputStream);
    outputStream.flush();
    outputStream.close();
} catch (Exception e) {
    e.printStackTrace();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!