绘制多个矩形而不调用invalidate()

时间:2011-06-06 00:36:54

标签: android android-canvas draw invalidation

我正在尝试绘制多个矩形。我希望能够手工绘制每个矩形。我可以绘制一个但是一旦我调用invalidate(),当然,画布会被清除。 是否有另一种方法来调用onDraw(),以便画布不被清除? 这就是我所拥有的:

我只是有一个扩展SurfaceView的类然后 覆盖onDraw

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

然后我覆盖一个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;
}

我这样做完全错了吗? :)

任何帮助都将不胜感激。

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以将每个矩形添加到列表中并按此迭代onDraw

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