An example can be found here compass.java. Api here
The translate() is a method of a 2D drawing context. The translate(x,y) method moves the canvas and its origin x units horizontally and y units vertically. In this syntax: x represents the distance that you want to move the origin of the canvas in the horizontal direction.
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:
What is actually happening is you are moving the coordinate system to a new place on the canvas:
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With