Android: Drawing multiple colors in Canvas

      Android provides a set of APIs for 2D-drawing that allow you to render your custom graphics on a canvas or modify the existing Views. In this example, we are going to see the use of Android Canvas on the UI Activity thread, and we are going to make a custom component, in order to achieve a small finger-drawing application.
      Now, start your eclipse and create a new android project!

1. Create a Custom Canvas View with these propreties:
- Setting up a new Canvas. This canvas will draw onto the defined Bitmap (onSizeChanged() method).
- Detecting and getting the x and y event coordinates in order to make our path moves (OnTouchEvent() method).
- Transforming the x,y event coordinates into path moves (moveTouch() method).
- Overriding onDraw() method, we will draw our path onto the canvas.
- Change line color in setPathColor() method.

Full DrawerView source code:
2. Create an Activity to use it.
In DrawerActivity layout, we:
- Set up an DrawerView in xml.
- Provide some color buttons to change lines color.
- Declaring "Save" button to save file to SD Card, "Clear" button to reset Canvas background.

activity_drawer.xml source code:
Full DrawerActivity  code:
3. Add permission to AndroidManifest.xml (read/write file on SD Card):
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
4. Build and run program, result like these:

pic name pic name pic name


Previous post
« Prev Post
Next post
Next Post »