nice guy nice guy - 1 month ago 7
Android Question

How to save LinearLayout as image after drawing (finger painting) on it

I am new to android, and creating a small application where I want to get an image from gallery and then after drawing on it (using finger paint) save it.

The problem I am having is after drawing, when I try to save the image it only saves the drawing with black background. The image taken from the gallery is not visible in the saved image.

After drawing on an image and saving it:



Actual Image saved:

enter image description here

Layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFCCCCCC"
android:orientation="vertical"
tools:context=".ImageActivity" >

<!-- layout for displaying save button -->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_gravity="center"
android:orientation="horizontal" >
<ImageButton
android:id="@+id/my_save_btn"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:contentDescription="@string/save"
android:src="@drawable/save" />
</LinearLayout>

<!-- layout that displays image taken from gallery and allows to finger paint-->
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:id="@+id/my_view_drawing_pad1"
android:layout_marginBottom="3dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="3dp"
android:layout_weight="1" >

<LinearLayout
android:id="@+id/my_view_drawing_pad"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
</LinearLayout>


ImageActivity.java onClick method to save image:

@Override
public void onClick(View view)
{
drawView.setDrawingCacheEnabled(true);
String imgSaved = MediaStore.Images.Media.insertImage(
getContentResolver(), drawView.getDrawingCache(), UUID.randomUUID()
.toString() + ".png", "drawing");

if (imgSaved != null)
{
Toast savedToast = Toast.makeText(getApplicationContext(),
"Drawing saved to Gallery!", Toast.LENGTH_SHORT);
savedToast.show();
} else {
Toast unsavedToast = Toast.makeText(getApplicationContext(),
"Oops! Image could not be saved.", Toast.LENGTH_SHORT);

unsavedToast.show();
}
drawView.destroyDrawingCache();
}


Could you please tell me, what am I missing here. Why my image is saved with black background?

Answer

Take a screen shot of the root layout and convert it into bitmap image and save it like following :

 LinearLayout v = (LinearLayout) findViewById(R.id.root_layout); 

    v.setDrawingCacheEnabled(true);

    v.buildDrawingCache(true);

    saveBm = Bitmap.createBitmap(v.getDrawingCache());

    v.setDrawingCacheEnabled(false);

Save this bitmap image where ever you want.

Comments