Search code examples
androidgeometrysurfaceviewtouch-event

Draw new Circle with each new Touch Event


I have a class that draws a circle at the point where the user touches. However, the circle disappears whenever a new point on the same surface is touched. I would like to keep the circle and draw a new one instead. Here is my current code.

import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

import java.util.Random;

public class ArtSurface extends SurfaceView implements Runnable, View.OnTouchListener {

    private SurfaceHolder aHolder;
    private Thread aThread;
    private boolean aFlag=false;

    private float aX;
    private float aY;
    private Paint aPaint;
private Random cRandom;
public int randomColor(){
    if (cRandom==null){
        cRandom=new Random();
    }
    int randomCol=0xff000000+256*256*cRandom.nextInt(256)+256*cRandom.nextInt(256)+cRandom.nextInt(256);
    return randomCol;
}
    public ArtSurface(Context context, AttributeSet attrs) {
        super(context, attrs);
        aHolder=getHolder();
        aX=-100;
        aY=-100;
        aPaint=new Paint();
        aPaint.setColor(randomColor());
    }
    public void resume(){
    aThread= new Thread(this);
    aFlag=true;
    aThread.start();
    }

    public void pause(){
        aFlag=false;
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        switch(motionEvent.getAction()){
            case MotionEvent.ACTION_DOWN:
                aX= motionEvent.getX();
                aY=motionEvent.getY();
                break;
            case MotionEvent.ACTION_UP:
                //Leave art where it is
                break;
        }
        return true;
    }

    @Override
    public void run() {
        while(aFlag){
            if(!aHolder.getSurface().isValid())
                continue;
            Canvas canvas=aHolder.lockCanvas();
            canvas.drawARGB(255,255,255,255);
            canvas.drawCircle(aX,aY,50,aPaint);

            aHolder.unlockCanvasAndPost(canvas);
        }



    }
}```

The way the code is currently, every new touch event causes a new circle to be drawn at the new point of touch. The previous circle is removed and I can only draw one circle at a time. My main aim is to have a new circle with a random color whenever the user touches a new point on the screen. All the other previous circles should remain where they were initially rendered. Thank you.


Solution

  • The line

    canvas.drawARGB(255,255,255,255);
    

    keeps drawing over the rendered circle. Removing it means that each new circle is visible on the canvas.