Posted By

Kenny_Van on 03/03/14


Tagged

java Drawing android


Versions (?)

Make a basic single touch drawing app for Android


 / Published in: Java
 

URL: http://creative-punch.net/2014/03/make-basic-single-touch-drawing-app-android/

Some times, android applications will consist of more than some buttons and some text. Or maybe you are looking into Android game development. Maybe you want to make a sketching application? You’ll have to know the basics about using the onTouch event. So let’s make a basic single touch drawing app on Android!

  1. package com.example.app;
  2.  
  3. import android.content.Context;
  4. import android.graphics.Canvas;
  5. import android.graphics.Color;
  6. import android.graphics.Paint;
  7. import android.graphics.Path;
  8. import android.util.AttributeSet;
  9. import android.view.MotionEvent;
  10. import android.view.View;
  11.  
  12. public class MainDrawingView extends View {
  13. private Paint paint = new Paint();
  14. private Path path = new Path();
  15.  
  16. public MainDrawingView(Context context, AttributeSet attrs) {
  17. super(context, attrs);
  18.  
  19. paint.setAntiAlias(true);
  20. paint.setStrokeWidth(5f);
  21. paint.setColor(Color.BLACK);
  22. paint.setStyle(Paint.Style.STROKE);
  23. paint.setStrokeJoin(Paint.Join.ROUND);
  24. }
  25.  
  26. @Override
  27. protected void onDraw(Canvas canvas) {
  28. canvas.drawPath(path, paint);
  29. }
  30.  
  31. @Override
  32. public boolean onTouchEvent(MotionEvent event) {
  33. float eventX = event.getX();
  34. float eventY = event.getY();
  35.  
  36. switch (event.getAction()) {
  37. case MotionEvent.ACTION_DOWN:
  38. path.moveTo(eventX, eventY);
  39. return true;
  40. case MotionEvent.ACTION_MOVE:
  41. path.lineTo(eventX, eventY);
  42. break;
  43. case MotionEvent.ACTION_UP:
  44. // nothing to do
  45. break;
  46. default:
  47. return false;
  48. }
  49.  
  50. // Schedules a repaint.
  51. invalidate();
  52. return true;
  53. }
  54. }

Report this snippet  

You need to login to post a comment.