In android there is no proper way to animate line growing from one point to another.

However I achieved it based on the below formula here. Since every one of us is dummy !
To divide an line into equal parts the respective starting point (x1,y1) and ending point (x2,y2) are,

(x,y) = (x1 + k(x2 - x1),y1 + k(y2 - y1))

where “k” = 1 / N (“N” is the total parts).

Step 1: Select (x1,y1) and (x2,y2) of line,

@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		super.onSizeChanged(w, h, oldw, oldh);
		
		//	starting point
		x1 = 50;
		y1 = 50;
		
		//	ending point
		x2 = getWidth() / 2 + getWidth() / 4;
		y2 = getHeight() / 2 + getHeight() / 4;
		
		Log.d("line xy xy", x1 + " : "+y1+" : "+x2 + " : "+y2);
		
		divideLineIntoEqualParts();
	}

Step 2: Dividing the line and adding respective points in a List.

	//	dividing line into 50 equal parts
	private void divideLineIntoEqualParts() {
		
		/*
		 * Courtesy : www.dummies.com
		 * (x,y) = (x1 + k(x2 - x1),y1 + k(y2 - y1))
		 * */
		
		listOfPoints.clear();
		for (int k = 1; k <= 50; k++) {
			listOfPoints.add(new PointF(x1 + ((k * (x2 - x1)) / 50),y1 + (k * (y2 - y1)) / 50));			
		}
		
		Log.d("listOfPoints : size : ",listOfPoints.size()+"");
	}

Step 3: onDraw(Canvas canvas)
Each time I try to draw a line from 0th point to another point hence it seems like gradually growing line.

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		
		if(inte < listOfPoints.size()){
			canvas.drawLine(listOfPoints.get(0).x, listOfPoints.get(0).y, listOfPoints.get(inte).x,listOfPoints.get(inte).y, paint);
			inte++;
			
			if(inte < listOfPoints.size()){
				invalidate();
			}
		}		
	}

Source code is available in github.

Enjoy! Happy coding!

5 thoughts on “How to animate line gradually growing from starting point to ending point !

Leave a comment