【问题标题】:Drawing Multiple rectangles without calling invalidate()绘制多个矩形而不调用 invalidate()
【发布时间】:2011-06-06 00:36:53
【问题描述】:

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

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

任何帮助将不胜感激。

谢谢!

【问题讨论】:

    标签: android android-canvas draw invalidation


    【解决方案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);
        }
    }
    

    【讨论】:

    • 谢谢!这正是我想要的:)
    猜你喜欢
    • 1970-01-01
    • 2019-08-27
    • 2015-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    • 2022-10-30
    • 1970-01-01
    相关资源
    最近更新 更多