Capture entire content of EditText into a picture

2019-04-14 03:59发布

问题:

I have to print the entire text of a text field into a picture. The reason is: I have to exchange messages with unsupported UTF-8 characters between Android and other web clients. By unsupported UTF-8 characters I mean missing fonts in Android (see this topic here ). I tried to use the direct way

Bitmap b;
EditText editText = (EditText) findViewById(R.id.editText);
editText.buildDrawingCache();
b = editText.getDrawingCache();
editText.destroyDrawingCache();

which works like a charm until I have multiple lines: The solution captures only the text which is visible to the user instead of the complete text inside of a long text field (scrollbars!).

I also tried another workaround by generating a picture from a stackoverflow answer. This prints the entire text but does not respect text formatting like newlines. But I don't want to handle all the stuff by myself.

I am forced to use Android 4.3 and earlier versions.

  1. Is there smart way to capture text into pictures? If not:
  2. Is it possible to modify the code above to get it work as expected?

回答1:

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();
}