Search code examples
javaandroidgeometrytouch-eventondraw

How to draw a new circle every time the screen is touched?


I want the program to draw a circle whenever the screen gets touched and if the screen gets touched on another position I want the program to draw a circle again but without deleting the old one!

Now my problem is that it doesn't just draw a new circle in addition to the old one. It draws a new circle and deletes the old one. I tried to find a solution but nothing worked.

So can anyone please help me?

So it's working now!

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.MotionEvent;
import android.view.View;

public class SingleTouchEventView extends View {
  private Paint paint = new Paint();
  List<Point> points = new ArrayList<Point>();


  public SingleTouchEventView(Context context, AttributeSet attrs) {
    super(context, attrs);}

  protected void onDraw(Canvas canvas){
      super.onDraw(canvas);
      paint.setColor(Color.GREEN);
      for(Point p: points){
           canvas.drawCircle(p.x, p.y, 20, paint);
      }
      invalidate();
    }

@Override
public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:

        Point p = new Point();
         p.x = (int)event.getX();
        p.y = (int)event.getY();
        points.add(p);
        invalidate();

    case MotionEvent.ACTION_MOVE:  // a pointer was moved
    case MotionEvent.ACTION_UP:
    case MotionEvent.ACTION_CANCEL: {
      break;
    }
    }
    invalidate();
    return true;  

}




}

Solution

  • You can achieve it by maintaining a list of points as a private instance variable:

    private List<Point> points = new ArrayList<Point>;
    

    Then you can add new points to this list every time a new touch event occurs:

    Point p = new Point();
    p.x = event.getX();
    p.y = event.getY();
    points.add(p);
    invalidate();
    

    Now in the onDraw() method you can print all the points in the list:

    paint.setColor(Color.GREEN);
    for(Point point: points){
         canvas.drawCircle(point.x, point.y, 20, paint);
    }
    invalidate();