How to draw a lot of rectangles on canvas with good performance?

I need to display a movie theater map with sectors, rows and seats. Currently, I have about 1000 places (filled rectangles) to draw, and I do this for each place by calling:

canvas.drawRect(seatRect, seatPaint)

My view should also support zooming, scrolling, and scrolling. Performance is terrible. I tried to improve it by explicitly enabling hardware acceleration, but nothing changed. It seems to have been enabled by default on my Nexus 4 (Api 22)

Could you suggest any methods for rendering a large number of rectangles at high speed? Thus, the animation of movement, scaling is smooth.

Custom View Class Code:

@Override
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    canvas.save();
    canvas.scale(mScaleFactor, mScaleFactor); // scaling support
    canvas.translate(mTranslateX, mTranslateY); // scrolling support

    if (mEventMap != null) {
        mEventMap.paint(canvas);
    }

    canvas.restore();
}

EventMap Code:

public void paint(Canvas canvas) {
    for (EventPlace place : places) {
        if (place.isSelected())
            placePaint.setColor(0xFF00FF00);
        else if (place.isAvailable())
            placePaint.setColor(place.getColor());
        else
            placePaint.setColor(0xFF000000);

        canvas.drawRect(place.getBounds(), placePaint);
    }
}

, onDraw, . ...

+4
1

, , , ( Rects ), Path, . , . - :

private void init() {
    mSelectedPath = new Path();
    mAvailablePath = new Path();
    mUnavalablePath = new Path();

    mAvailablePaint = new Paint();
    mSelectedPaint = new Paint();
    mUnavalablePaint = new Paint();

    mUnavalablePaint.setColor(Color.RED);
    mSelectedPaint.setColor(Color.YELLOW);
    mAvailablePaint.setColor(Color.GREEN);

    for (EventPlace place : mData) {
        if (place.isSelected())
            mSelectedPath.addRect(rectF, Path.Direction.CW);
        else if (place.isAvailable())
            mAvailablePath.addRect(rectF, Path.Direction.CW);
        else
            mUnavalablePath.addRect(rectF, Path.Direction.CW);
    }
}

, , - :

public void setData(List<EventPlace> data) {
    mData = data;
    init();
    invalidate();
}

, , , init, . onDraw:

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    canvas.save();
    canvas.scale(mScaleFactor, mScaleFactor); // scaling support
    canvas.translate(mTranslateX, mTranslateY); // scrolling support

    canvas.drawPath(mAvailablePath, mAvailablePaint);
    canvas.drawPath(mUnavalablePath, mUnavalablePaint);
    canvas.drawPath(mSelectedPath, mSelectedPaint);

    canvas.restore();
}

, , Rect, , .

Rect, 200 rects, ,

+2

Source: https://habr.com/ru/post/1599319/


All Articles