Wozza
Wozza

Reputation: 622

Drawing to the canvas on Android - screen flickering/tearing

I have an isometric map which I draw to the canvas. When I try and move the map around, these black lines flicker in between some of the tiles making the whole thing look rather shoddy.

Here is the relevant code from my updating thread

public void run() {
    Canvas c;
    while (isRunning){
        c = null;
        try {
            c = cellMap.getHolder().lockCanvas(null);
            synchronized (cellMap.getHolder()) {
                cellMap.onDraw(c);
            }
        } finally {
            if( c != null){
                cellMap.getHolder().unlockCanvasAndPost(c);
            }
        }
    }
}

and from my CellMap class (which extends SurfaceView):

    public void onDraw(Canvas canvas){
    canvas.drawColor(Color.BLACK);
    int x = 0;
    int y = 0;

    for(int i = 0; i < mapSize; i++){
        for(int j = 0; j < mapSize; j++){
            x = (i-j) * 30 + xOffset;
            y = (i+j) * 15 + yOffset;
            mapCells[i][j].draw(canvas, paint, x, y);
        }
    }

mapCells[][] is an array of objects which contain the Bitmap image that needs to be drawn. The draw() function is only 1 line canvas.drawBitmap(bitmapImage, x, y, null)

I have discovered that removing the line Canvas.draw(Color.black) gets rid of the flicker. However, when I move the map the canvas is not cleared so I still see the image from the previous frames. I'd imagine it is because it is taking too long to draw the bitmaps? but the map is only very small at the moment.

Upvotes: 1

Views: 1947

Answers (1)

Wozza
Wozza

Reputation: 622

I found the problem. When moving the map, the offset values were being changed. This lead to sections of the map being drawn temporarily with different offset values - creating the tearing. duh!

I solved this by copying the xOffset and yOffset values at the start of the onDraw() method, and using those values for the update.

Upvotes: 2

Related Questions