What does canvas.translate do?

An example can be found here compass.java. Api here


Even when I first answered this question a few years ago, I didn't really understand how Canvas transforms (like translate, rotate, etc.) worked. I used to think that translate moved the thing that you were drawing. Actually, translate moves the entire coordinate system. This has the desired effect of also moving the thing you are drawing.

On your screen it looks like you are moving the drawing:

Android Canvas.translate() method

What is actually happening is you are moving the coordinate system to a new place on the canvas:

enter image description here

I draw the tree first at (0,0). Then I translate the origin of the coordinate system to some other spot on the canvas. Then I draw the tree again at (0,0). This way my drawing code doesn't have to change anything at all. Only the coordinate system changes.

Normally (0,0) is at the top left of your view. Doing Canvas.translate moves it to some other part of your view.

Saving and Restoring the Coordinate System

You can do save() and restore() to get back to your original coordinate system.

// draw the tree the first time
canvas.drawBitmap(tree, 0, 0, mPaint);

// draw the tree the second time
canvas.save();
canvas.translate(dx, dy); // dx = change in x, dy = change in y
canvas.drawBitmap(tree, 0, 0, mPaint); // draw still thinks it is at (0,0)
canvas.restore(); // undo the translate 

When you restore, the drawing is already on the canvas. Restoring doesn't change that. It just moves the coordinate system back to wherever it was when you saved it.

Why Translate

Note that you could achieve the same affect by changing the x,y coordinates of the draw method:

// draw the tree the first time
canvas.drawBitmap(tree, x, y, mPaint);

// update the x,y coordinates
x += dx;
y += dy;

// draw the tree the second time
canvas.drawBitmap(tree, x, y, mPaint);

This might be more intuitive coming from a math background. However, when you are translating, rotating, and scaling your image, it is often much easy to keep your drawing logic the same and just transform the canvas. Recalculating x and y for every draw could be very expensive.


Translate - Basically do what it says. Just translate the canvas using x,y. If you want to draw two objects and the one is just translation of the other e.g x2 = x1 + 50 for each point . You don't have to make all your calculations again for the second object but you can just translate the canvas and draw again the same object. I hope this example will help you.