Draw beautiful diagram effortlessly on ipad. Click here to know more..

Sunday, January 15, 2012

Drawing and erasing using touch on Android

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:
  • 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:
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:orientation="horizontal"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:id="@+id/drawPanel">
    </LinearLayout>
and from the code, add the custom view to this LinearLayout as:
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        LinearLayout ll = (LinearLayout)findViewById(R.id.drawPanel);
        DrawPanel drawingPanel = new DrawPanel(getApplicationContext());
        ll.addView(drawingPanel);
    }
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


public class DrawPanel extends View { 
public DrawPanel(Context context) {
  super(context);
  points = new ArrayList();
  strokes = new ArrayList();
  paint = createPaint(Color.GREEN, 8);
 }

 @Override
 public void onDraw(Canvas c){
  super.onDraw(c);
  this.setBackgroundColor(Color.WHITE);
  for(Object obj: strokes){
   drawStroke((ArrayList)obj, c);
  }
  
  drawStroke(points, c);
 }
 
 @Override
 public boolean onTouchEvent(MotionEvent event){
  if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
   points.add(new Point((int)event.getX(), (int)event.getY()));
   invalidate();
  }
  
  if(event.getActionMasked() == MotionEvent.ACTION_UP){
   this.strokes.add(points);
   points = new ArrayList();
  }
  
  return true;
 }
 
 private void drawStroke(ArrayList stroke, Canvas c){
  if (stroke.size() > 0) {
   Point p0 = (Point)stroke.get(0);
   for (int i = 1; i < stroke.size(); i++) {
    Point p1 = (Point)stroke.get(i);
    c.drawLine(p0.x, p0.y, p1.x, p1.y, paint);
    p0 = p1;
   }
  }
 }
 
 private Paint createPaint(int color, float width){
  Paint temp = new Paint();
  temp.setStyle(Paint.Style.STROKE);
  temp.setAntiAlias(true);
  temp.setColor(color);
  temp.setStrokeWidth(width);
  temp.setStrokeCap(Cap.ROUND);
  
  return temp;
 }
 
 private Paint paint;
 private ArrayList points;
 private ArrayList strokes;
}

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.

50 comments:

  1. hank you very much. Simple and accessible.

    ReplyDelete
  2. Can you mail me code on swapnil_go20@yahoo.co.in ???
    I need it.

    Please do the needful...

    ReplyDelete
  3. Dang, I so need this... any chance you can tell me how to get this line to work ?
    from the on draw method for(ArrayList stroke: strokes){
    drawStroke(stroke, c);

    I get a type mismatch error on this line...

    Thanks for this code ( and fix hopefully ) Thanks.

    ReplyDelete
  4. thanks...please add more drawing samples

    ReplyDelete
  5. It 's very helpful for me! Thank you very much!

    ReplyDelete
  6. how can i do it for multitouch ?? here only single line is drawn I want to draw full area which I touch... Can anyone help me??

    ReplyDelete
  7. A well-designed custom view is much like whatever other well-designed class.It encapsulates a particular set of functionality with a simple to utilize interface,it utilizes CPU and memory efficiently, and so forth.Notwithstanding being a well-designed class,however,a custom view should:Conform to Android standards,Provide custom style-able attributes that work with Android XML layouts,Send accessibility events,Be compatible with multiple Android platforms.
    ----------------------------------------------
    hidden movie game for android

    ReplyDelete
  8. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    Java Online Training Java Online Training JavaEE Training in Chennai Java EE Training in Chennai

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. مزايا نقل الأثاث من قبل
    واحدة من أهم ميزات شركة لنقل الأثاث في الرياض ، والتي تميزت عن غيرها من الشركات المتخصصة في مجال نقل الأثاث ، حيث توفر ، كأفضل شركة لنقل الأثاث في الرياض ،شركة نقل عفش
    شركة نقل عفش من الرياض الى الامارات

    شركة نقل اثاث من الرياض الى الامارات

    شركة نقل عفش بالجبيل

    ReplyDelete
  11. EaseUS Data Recovery Pro License Code With Crack 2020


    Easeus Data Recovery Activation Key often is the biggest costless data recovery software. By using this one can recuperate arranged, removed and as well as dropped details. You can recuperate it by using a laptop or Particular Computer and detachable system speedily as well as amazingly quite simply. It quite often takes place that the facts in the drive or process is dropped due to a crash of plan or unintended deletion. Easeus data recovery 2020100 % crack with license code Free of cost Download is just one of the greatest data recovery software applications. EaseUS Data Recovery 12 Total most current version no cost Download + Pretty & cute patch is the Totally totally free Version. It is able artist that one can make use of to recover help and advice via your hard disk drive, UNIVERSAL SERIES BUS drives, memory space cards, also as other removable storage devices too. It shows to be an amazing product for each Mac in the process as windows

    ReplyDelete
  12. Waking around bird-chirpings over a vivid, new sunny morning is enjoyable. But if the chirping is accompanied by a lovey-dovey good morning message from your significant other, then it charges you up like a cup of coffee.
    Have a passion for isn't a universal need to get. It is really rather an emotion that drives mankind! And there exist plenty of methods to express this take pleasure in. Sending warm and loving good morning messages is simply one of them.
    So, in order to sparkle your wife’s day, MomJunction has amazing Romantic Good Morning Quotes For Wife. We wager your wife will be swept off her ft.

    ReplyDelete
  13. Its a indisputable fact that how wonderful a person’s day ends up really being mostly relies upon on how they started out it on the morning. It is usually for this reason why it can be important that you just begin the process of your day over a beneficial note. And what more beneficial process to do this than receiving a heartfelt good morning concept from a cherished one?!
    They're extraordinary birthday messages ranging from sweet to inspirational that one could deliver to your beloved mom to offer her a good begin the process of on the morning and enhance her chance of owning a gorgeous day. Visit for Lovely Quotes Good Morning Mother

    ReplyDelete
  14. This comment has been removed by the author.

    ReplyDelete
  15. I am a student, i am running my blog how2wish. I love to write on several social topics like Funny Graduation Announcements, Everyday Quotes and much more.

    ReplyDelete
  16. I'm a teacher and I read the web.April Fool Quotes. I love to write on several social topics like Funny Graduation Announcements, Everyday Quotes and much more.

    ReplyDelete
  17. I am a bloger and creat web link. april fools jokes text messages. I love to write on several social topics like Funny Graduation Announcements, Everyday Quotes and much more.

    ReplyDelete
  18. https://cracksmod.com/4k-stogram-crack-key/
    4K Stogram can download full media content from multiple accounts of customers at the same time. You can upgrade the previously described accounts in the application form, which will allow you to download the latest photographs and video materials distributed within them. 4K Stogram License Key will deliver a straightforward way to get access to and save Instagram pictures. It allows you to view the following list of the user. You can also subscribe to the following account list of any Instagram user. This application is an excellent tool that is very easy to use. It is available for PC, Mac, and Linux devices.Among many functions, this program allows you to save photographs from different accounts together and save those photos to JPEG on Macintosh personal computer.

    ReplyDelete
  19. https://shehrozpc.com/movavi-video-editor-crack/
    Movavi Video Editor 2020 Crack latest update comes up with a feature of drag and drop, cut, copy and paste, etc. This feature makes it extra attractive, because you can easily cut a person from your video and paste it anywhere you want. This feature makes an advanced innovation in worlds mind to create highly awesome results. You can also merge your voices, pictures and video clips to create shinning and professional videos. These features of this software put your work on a next and advanced level of video editing. With this, you can easily produce Bollywood type’s videos and films.

    ReplyDelete
  20. https://letcracks.com/connectify-hotspot-pro-crack/
    Connectify Hotspot Pro Serial Key is developed by Connectify Inc. This company is well known for providing the users with sufficient tools for makings the work-life of user’s easy. Connectify Hotspot Pro is also an example of such a program. Before it was introduced in the market, the users had no idea what they were missing. As soon as the program was release, people started using the program and showing support.This inspired many other developers to peruse this idea. Now there are several programs of a similar genre in the market, but Connectify Hotspot Pro Serial Key is the best one among them. But this program has solved that problem, and the users can now stream and use the internet on multiple devices simultaneously.

    ReplyDelete
  21. https://cracksmad.com/speedify-crack/
    Speedify Crack Torrent is a brand new type of Virtue Private Network (VPN) and a new internet tool that is here to keep the network wholly secured. This program collectively combines the Wi-Fi and cellular networks to create one solely robust system. Both Windows OS and macOS devices equally support this program. This VPN allows the fastest connectivity and smooth connection whiteout slowing down the speed of the internet.

    ReplyDelete
  22. https://chserialkey.com/antares-autotune-pro-crack/
    Antares AutoTune Pro Serial Key are three main modes of this powerful and engaging application software. These three modes are complete, flexible, effective, efficient and impressive on their own use and function. The first model is the Classic mode comes with many impressive features that not only increase the pleasure of your musical journey but also let you experience the environment of the studio in the best professional way ever. The unique and different features of the Classic mode, such as, sketchers, flex tune, humanize, throat modelling and low-latency come up with a variety of efficiency flexibility that let you have a real-time experience of recording your music album and let you feel like you are performing live on the stage.

    ReplyDelete
  23. https://chproductkey.com/aomei-partition-assistant-crack/
    AOMEI Partition Assistant Torrent is a very handy software and provides you with solutions for many of your disk partition problems. For the new users, it comes along with the step by step wizards that makes it very easy for the new users to understand and operate it. It is a very intuitive software that provides you with many useful suggestions and notes. Apart from its impressive interface, it enables you to plan your tasks as well, and it executes all the given tasks at the provided time. It provides you with no data loss conversion between dynamic to basic disk.

    ReplyDelete
  24. https://zscrack.com/dvdfab-crack/
    DVDFab Crack is a powerful software for DVD burning. This software offers great features for backup, breaking CD and DVD locks. You can convert video and decrypt blur files as well. A user is easily able to restore lost DVD data as well. In general, it is one of the most efficient DVD management software for its users. From the graphical interface, you can point to the correct functionality on the table and all the options as well. Therefore, it makes sure no option remains behind in the spam program for the speed working of a user.

    ReplyDelete
  25. https://zsactivationkey.com/spotify-crack/
    Spotify Premium Crack is a Music App, which lets user stream(play) music, songs or even podcast. You can also download them in the app to enjoy the limitless number of tracks when having no internet. There is also a premium version where, unlike the free version, there would be no ads. For students, there are also some discounts on the paid version which they can avail easily through their student id. The free version in the form of mobile as well as a desktop application, but you need to get Spotify Premium Crack from ZS Activation Key for full services.

    ReplyDelete
  26. https://ziapc.org/smadav-pro-crack/
    Smadav Pro Crack 2020 is the best antivirus program that gives you second pro layer protection to shield your data from virus attack. This software is the best expression antivirus software that is made possible for all Windows OS. Most antivirus software cannot install other antiviruses. Also, antiviruses principally designed for managing reality in your PC.

    ReplyDelete
  27. https://cracksway.com/dvdfab-passkey-crack/
    DVDFab Passkey Crack supports Blu-ray discs, which are now used more often than DVDs. It is because Blu Rays provide more increase in video quality of the movies. There are some Blu-ray discs that cannot be played on computers. They are encrypted with protection against piracy. If you want to access these movies and content, this program will help you in achieving your goal. It is a feature-packed software that works smoothly without affecting the quality of the vide. You can remove region code enhancement and an analog protection system. With this program, you can get rid of the user operation prohibition services.

    ReplyDelete
  28. thanks for your post i have found the information that i want on your blog its such a nice theme .
    thanks for your infomative post .
    Free Full Pro Keys for Windows & Mac software

    Full Pro Keys

    ReplyDelete
  29. thanks for your post i have found the information that i want on your blog its such a nice theme .
    thanks for your infomative post .
    Free Download Oceanofgames for Windows & Mac software PC Games

    Ocean of Games

    ReplyDelete
  30. thanks for your post i have found the information that i want on your blog its such a nice theme .
    thanks for your infomative post .
    Free Download Oceanofgames for Windows & Mac software PC Games

    Ocean of Games

    ReplyDelete
  31. https://shahzifpc.com/
    This site contains unequivocal software articles which, to be perfectly honest, appear to be the key and key to a solitary, fit software installation for you. This is where you can find support for any software installation, usage and break.

    ReplyDelete
  32. https://cracksmat.com/
    This site has clear software articles which shows up, point of fact, to be a key and key for you single, fit software installation.This is the spot you can get helps for any software installation, usage and cracked.

    ReplyDelete
  33. https://crackdad.com/
    This site has clear software articles which appears, without a doubt, to be a key and key for you single, fit software installation.This is the spot you can get helps for any software installation, usage a

    ReplyDelete
  34. https://serialkeygen.org/
    This site has clear software articles which shows up, doubtlessly, to be a key and key for you single, fit software installation.This is the spot you can get helps for any software installation, usage and cracked.

    ReplyDelete
  35. thanks for your post i have found the information that i want on your blog its such a nice theme .
    thanks for your infomative post .
    Free Full Pro Keys for Windows & Mac software

    Full Pro Keys

    ReplyDelete
  36. thanks for your post i have found the information that i want on your blog its such a nice theme .
    thanks for your infomative post .
    Free Full Pro Keys for Windows & Mac software

    Full Pro Keys

    ReplyDelete
  37. https://crackedhere.com/pinnacle-studio-pro-cracked-with-torrent/
    Pinnacle Studio 23 Crack is a video editing software. It is introduced by the ‘Pinnacle systems’. The program permits you to change video material in CD, DVD video, AVCHD or Blu ray formats, etc. Pinnacle can run on windows 10, 8, 8.1, 7, and Windows compatible sound card.

    ReplyDelete
  38. https://fullycrack.org/autodesk-fusion-360-torrent-free-cracked/
    Autodesk Fusion 360 Cracked is the initial 3D CAD, CAM, and CAE software. It connected your complete creative development procedures, in one cloud-based platform. It is introduced by the ‘Autodesk’. The program operates on Microsoft Windows, computers, and mac and mobile devices.

    ReplyDelete
  39. https://activatorskey.com/mirc-keygen-plus-registration-code/
    mIRC Crack has the support for COM tools like DLLs, and sockets canvass drawing. It also supports input device reading, regular expressions, and dialog boxes. You can use all these functions in many other ways rather than chatting.

    ReplyDelete
  40. https://autocracked.org/lumion-crack-with-torrent/
    Lumion Crack is an attractive and effective tool for a buildup 3D environment. It is the type of 3D software that works efficiently and quickly comparatively others.

    ReplyDelete
  41. https://greencracks.com/arcgis-torrent-crack/
    ArcGIS Crack is the Geographic Information System. Solve the different map problem. Work in different window operating system. Change the different maps. But best and suitable with window 7 edit the mapping process. Mean edit the map. Add the multiple things on the map. Clear the map. Mean user easy to understand the maps.

    ReplyDelete
  42. https://thinkcrack.com/wondershare-video-converter-ultimate-crack-license-key/
    Wondershare Video Converter Ultimate Crack is video editing software. This software work as window software for computer. And presented as app form now. During using in the computer user easily modify the different video. And during app form user modify the video on a mobile phone. But both modify the video. Edit the video. Add the different effect on video. Crop some part of the video.

    ReplyDelete
  43. https://autocracking.com/winzip-crack-plus-activation-code/
    Winzip Crack is a useful place where you can easily find Activators, Patch, Full version software Free Download, License key, serial key, keygen, Activation Key and Torrents. Get all of these by easily just on a single click.

    ReplyDelete
  44. https://crackedsoftpc.com/driver-easy-crack-download-here/
    Driver Easy Crack is easy that locates system-lacking motorists and frees them from the computer system. In addition, analyze the hottest version of motorists them with all recent. It scans the full network and informs that the person of most of the motorists’ factors. In any case, it supplies an individual using an easy-to-use user interface with a lot of comprised programs.

    ReplyDelete
  45. TeraCopy Pro Crack
    Teracopy Crack is software for Windows that plays the role of earning a lot more successful copying procedures. It will find all the characteristics to recoup and also transfer glitches and then pause and restart the document. Also, it comes with a paid variation. And provides a lot of more special purposes to function on the files. The software enables consumers to improve quite a few preferences inside their look as well as tasks. But it’s critical to listen while employing this software since it does not have any tools to recoup files.

    ReplyDelete
  46. GetFLV Pro Crack is the determination of them that can be utilized to need it initially and without any problem. Along these lines, this device can be utilized to just all the destinations, and the strategy can be part of the division.

    ReplyDelete