开发者

Drawing Multiple rectangles without calling invalidate()

开发者 https://www.devze.com 2023-03-11 10:32 出处:网络
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.

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;
            br开发者_JAVA技巧eak;
        case MotionEvent.ACTION_UP:

            break;
    }

    return true;
}

Am I doing this completely wrong? :)

Any help would be appreciated.

Thanks!


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);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号