Search code examples
androidandroid-canvasdrawinvalidation

Drawing Multiple rectangles without calling invalidate()


I'm trying to draw multiple rectangles. I want to be able to draw each rectangle by hand though. I can draw one but then once I call invalidate(), of course, the canvas gets cleared. Is there another way to call the onDraw() so that the canvas doesn't get cleared? Here's what I have:

I simply have a class which extends a SurfaceView and then Override the onDraw

@Override
protected void onDraw(Canvas canvas) 
{
    Paint paint = new Paint();
    paint.setColor(Color.BLUE);
    canvas.drawRect(xCoor, yCoor, rectW, rectH, paint);
}

And then I Override an OnTouchEvent

@Override
public boolean onTouchEvent (MotionEvent event) 
{

    downX = Math.round(event.getX());
    downY = Math.round(event.getY());

    invalidate();    //clears canvas which I don't want
    switch (event.getAction())
    {
        case MotionEvent.ACTION_DOWN:
            xCoor = downX;
            yCoor = downY;
            rectH = 0;
            rectW = 0;
            break;
        case MotionEvent.ACTION_MOVE:
            rectH = downY;
            rectW = downX;
            break;
        case MotionEvent.ACTION_UP:

            break;
    }

    return true;
}

Am I doing this completely wrong? :)

Any help would be appreciated.

Thanks!


Solution

  • You could add each rectangle to a list and iterate it onDraw like this:

    import android.graphics.Rect;
    
    private ArrayList<Rect> rectangles = new ArrayList<Rect>();
    
    @Override
    public boolean onTouchEvent (MotionEvent event) {
        // ...
        case MotionEvent.ACTION_UP:
            rectangles.add(new Rect(xCoor, yCoor, rectW, rectH));
            break;
        // ...
    }
    
    @Override
    protected void onDraw(Canvas canvas) {
        Paint paint = new Paint();
        paint.setColor(Color.BLUE);
        for (Rect rect : rectangles) {
            canvas.drawRect(rect, paint);
        }
    }