I have an simple EditText
inside an Activity
and I want to create a Bitmap
Image from that EditText
and content of the EditText
. The Image
should look same as the EditText
and its content
.
Here is how I want the Image should look like
, though this is an EditText but I want a Bitmap which should look same as this. So, how can I achieve this? Any idea would be great.
This is my code,
public class EditTextPinchZoomActivity extends Activity {
EditText editText;
ImageView imageView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView) findViewById(R.id.image_view);
editText = (EditText) findViewById(R.id.edit_text);
editText.buildDrawingCache();
}
public void myOnClick(View view) {
switch (view.getId()) {
case R.id.btn:
imageView.setImageBitmap(editText.getDrawingCache());
break;
default:
break;
}
}
}
You can get the bitmap by building the drawing cache. This should work.
EditText edit = (EditText)findViewById(R.id.edit);
edit.buildDrawingCache();
ImageView img = (ImageView)findViewById(R.id.test);
img.setImageBitmap(edit.getDrawingCache());
Lalit when you try to build the cache in the onCreate method, the drawing hasn't happened yet so the drawingCache should have nothing. Either put the buildDrawingChache method in the onClick method. Or use the following code in onCreate.
ViewTreeObserver vto = editText.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
editText.buildDrawingCache();
}
});
But I think building the cache in the onClick method will be proper as the screen will be drawn by then. And other thing I remebered is, if you entering text after the onCreate, then you should build the cache after that. So try the first method.
ViewTreeObserver
Its a global layout listener to a view or viewgroup which keeps getting called when anyhing changes to the layout. I normally use this in cases where I need to get width and height's of views in the onCreate method. Without this the value will always be 0 as no drawing or measuring has taken place.
Suppose you had a requirement to keep updating your imageview of the edittext as you type, you can use this and just remove the first line where I remove the listener. The listener will be called for every character you type even when the cursor blinks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With