Drawing/Erasing using touch is a common feature in many mobile phone/tablet based apps. Writing code for this feature is pretty simple for android. Here are steps to do that:
This code finds the LinearLayout object which was defined in XML and then adds an object of DrawPanel to this. The DrawPanel is the custom View class which is being used for drawing. Here is the implementation of DrawPanel
The above code is for drawing. With a small tweak, erasing can be implemented. While erasing, set the paint color as that of background, that's it!!
The above code is used in Scratchpad, a drawing app for Android tablets.
- add a custom view on which you will draw.
- process touch event on view.
- on touch event, record points where touch event occurred.
- in onDraw method, draw points that were recorded.
Adding a custom view:
We will derive a class from View class for implementing drawing canvas. And we will add this to UI tree. To add this to UITree, create a LinearLayout in which the custom view will be added. The LinearLayout is declared in layout xml as:
and from the code, add the custom view to this LinearLayout as:This code finds the LinearLayout object which was defined in XML and then adds an object of DrawPanel to this. The DrawPanel is the custom View class which is being used for drawing. Here is the implementation of DrawPanel
The above code is for drawing. With a small tweak, erasing can be implemented. While erasing, set the paint color as that of background, that's it!!
The above code is used in Scratchpad, a drawing app for Android tablets.