Android Paint Example


In this example, we demonstrate how to draw/paint on canvas when the user touches and drags on the screen. Here we will create a custom view class called 'PaintView' which will be used as the contentview for the 'MainActivity'.

So lets start:

1. Create a new project File ->New -> Project ->Android ->Android Application Project. While creating a new project, name the activity as MainActivity(MainActivity.java).Press Ctrl+Shift+O for missing imports after typing the code

MainActivity.java
public class MainActivity extends Activity {

 PaintView paintView;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);
  requestWindowFeature(Window.FEATURE_NO_TITLE);

  paintView = new PaintView(this);
  setContentView(paintView);
  paintView.requestFocus();
 }

}

2. Now create a new class by rightclicking the /src/<package-name> and select class to create a new class named PaintView(PaintView.java).Press Ctrl+Shift+O for missing imports after typing the code

PaintView.java
public class PaintView extends View implements OnTouchListener {
 private static final String TAG = "PaintView";

 List<Point> points = new ArrayList<Point>();
 Paint paint = new Paint();

 public PaintView(Context context) {
  super(context);
  setFocusable(true);
  setFocusableInTouchMode(true);

  this.setOnTouchListener(this);

  paint.setColor(Color.GREEN);
  paint.setAntiAlias(true);
 }

 @Override
 public void onDraw(Canvas canvas) {
  for (Point point : points) {
   canvas.drawCircle(point.x, point.y, 2, paint);
  }
 }

 public boolean onTouch(View view, MotionEvent event) {
  Point point = new Point();
  point.x = event.getX();
  point.y = event.getY();
  points.add(point);
  invalidate();
  Log.d(TAG, "point: " + point);
  return true;
 }
}

class Point {
 float x, y;

 @Override
 public String toString() {
  return x + ", " + y;
 }
}

3.We did not create any .xml file for UI since the above two files are the only significant files for this example. Run the project by rightclicking project Run as → android project. Try enhancing this by providing color options,brush styles etc.,  


Output:

The output of this example after drawing would be something like this