Welcome to the part 2 of the Sign It! app series on roadtodroid. In this post we explore the method to save our drawing from the canvas to a bitmap image & also to store that image onto the system storage.
For this part I will use the app made till the previous post and build onto it only. So I recommend your to go through that one first.
1. Update the onDraw() method to create Bitmap for the canvas
- In the onDraw() method , previously we only drew to the view using
- We now create a new temporary canvas and call it singleuseCanvas.
- Also we create a global Bitmap called myBitmap to store each update to singleuseCanvas.
- We first set myBitmap to singleuseCanvas using
- We then draw to the new canvas using
- And finally we draw to the Bitmap using
2. Save the Bitmap when Save on Action Bar is pressed
- When the save button is pressed we call the function saveMyBitmap(); in the CanvasView.
- Here we first create an empty FileOutputStream (For more visit : http://developer.android.com/reference/java/io/FileOutputStream.html).
- Now we get the root path for the External SD card using
- After this we create a new File object giving its constructor the path of the directory we want our images to be stored on. This is done by appending root string to "Sign It" folder(You can give any name). The File.separator is the devices' default & specific file separator .
- Then we just create the string containing the name we want to give our file (I have used the systems current date & time), create another file containing root and file name, give that to the FileOutputStream.
- We use compress method on myBitmap to compress and put it on the output stream.
- Finally we flush and close the stream.
- Also remember to add the following line to the manifest file:
3. Update Gallery
- Now the next thing is to notify the gallery to update its data when we save a new image to our phone storage. To accomplish this we MediaScannerConnection class.
- The context used in the function is the context of our MainActivity which we will pass later in the MainActivity.
- The code is quite straight forward.
4. Modify the MainActivity
- In the main activity just add the corresponding function calls in the onOptionsItemSelected.
- Also here we add a new method called to open gallery from our app only. The ACTION_VIEW specifies that some data is to be shown to user of which the Uri we have parsed. Also we add a flag to the intent , which restricts gallery to be kept in stack.
- And now just run the project.
|Click Save icon|
|Images stored in gallery|
|CLICK THE ICON|