2

我正在尝试绘制多个矩形。我希望能够手动绘制每个矩形。我可以画一个,但是一旦我调用 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;
}

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

任何帮助,将不胜感激。

谢谢!

4

1 回答 1

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);
    }
}
于 2011-06-06T14:32:50.717 回答