Creating A Simple Custom Drawing View In Android within 5 Steps.

This story shows how to create a simple canvas view which influence drawing.

Android structure has huge view classes for communicating with user and performing various tasks but sometime our application has needs that are not covered by the build-in views.

To build a view we need 4 ingredient that are Bitmap, Canvas, Drawing primitive(Path) & Paint.

Lets get started!

First we have to Extend View class with our class and implement constructor methods

1. Initialize drawing primitive and paint in all the constructors.

Initialization.
private int pathIndex = 0;
private ArrayList<Path> pathLists = new ArrayList<>();
private ArrayList<Paint> paintLists = new ArrayList<>();
private float startX = 0F;
private float startY = 0F;
private void init() {
pathLists.add(new Path());
paintLists.add(createPaint());
pathIndex++;
}
Create instance of Paint.
Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(3F);
Create nstance of Path and moving current position.
Path path = new Path();
startX = event.getX();
startY = event.getY();

path.moveTo(startX, startY);

2. Override the onDraw method and update Canvas to draw the Path.

Update path by canvas.
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
    canvas.drawColor(Color.WHITE);

for (int index = 0; i < pathIndex; index++) {
Path path = pathLists.get(index);
Paint paint = paintLists.get(index);

canvas.drawPath(path, paint);
}
}

3. Override the onTouchEvent and set event listener for drawing

A view is not only responsible for drawing but also to handle events.
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
----
break;
case MotionEvent.ACTION_MOVE:
----
break;
default:
break;
}
// Invalidate the whole view. If the view is visible.
invalidate();
return true;
}
Action on Move Motion Event.
float x = event.getX();
float y = event.getY();
Path path = pathLists.get(pathIndex - 1);;
path.lineTo(x, y);
Action on Down Motion Event.
updateIndex(createPath(event));

4. Handle Path Index for ”Undo” and “Redo” method.

Update instances of Path and Paint.
pathIndex == pathLists.size())
pathLists.add(path);
paintLists.add(createPaint());
pathIndex++;

On Final step 5. Add the custom class in xml.

See the magic!

What to you think about this 5 steps to create canvas view?

If I missed something. Let me know in the comments and I will look into it!