FallingRain
FallingRain

Reputation: 37

How to avoid spend long time in onDraw?

I am writing an app to draw some data (map of subway data), and the map can be moved/scaled when user touch the screen. Now I am using View to draw the map, the map is being drawed in Canvas when onDraw(Canvas canvas) called.

I caculate the translate x/y and scale when onTouchEvent called and then call invalidate() to refresh the map. The onDraw method looks like this:

@Override
protected void onDraw(Canvas canvas) {
    canvas.save();
    canvas.translate(nowPosX, nowPosY);
    canvas.scale(mScaleFactor, mScaleFactor);
    canvas.drawColor(Color.WHITE);

    for (Subways.Line line : subwayData.getLineList()) {
        for (Subways.Line.Stations:line.getStationList) {
            canvas.drawLine();
            canvas.drawText();
            canvas.drawCircle();
        }
    }

    canvas.restore();
    super.onDraw(canvas);
}

But I have a problem now. Every time I move/scale the map, I need to redraw everything and the data is so many and spend lot of time. It will slow when I move/scale the map.

I tried to draw in Bitmap first and move/scale the bitmap everytime onDraw called. But if bitmap is small, it will looks fuzzy when I scale. If bitmap is big, it may cause OutOfMemoryError.

Is there any way to solve my problem?

Upvotes: 2

Views: 796

Answers (2)

Patrick Chan
Patrick Chan

Reputation: 1029

You can prepare the map with lines, circles and text drawn on it into many Bitmaps before showing the map to the screen.

Then modify the onDraw() method to make it only draw certain breakdown bitmaps in correct scale.

Upvotes: 1

Augusto Ferrarini
Augusto Ferrarini

Reputation: 91

On some older Android versions you can improve performance by drawing all the bitmaps at once and all the text at once. Other possibility is to create a Path for each text you have, cache them and use the cache for drawing the Paths everytime a redraw is needed.

Upvotes: 1

Related Questions