Reputation: 33871
I have some objects which I draw onto a Canvas as part of a SurfaceView. I want to be able to rotate these programmatically, e.g. myParticle.setRotation(90);
Here's my (simplified) code to draw the Particle at the moment:
public class Particle {
public void draw(Canvas canvas){
image.setBounds((int)(xPos), (int)(yPos), (int)(xPos+radius), (int)(yPos+radius));
image.draw(canvas);
}
}
Upvotes: 15
Views: 29761
Reputation: 3163
To me it seems cleaner to do this:
Matrix rotator = new Matrix();
// rotate around (0,0)
rotator.postRotate(90);
// or, rotate around x,y
// NOTE: coords in bitmap-space!
int xRotate = ...
int yRotate = ...
rotator.postRotate(90, xRotate, yRotate);
// to set the position in canvas where the bitmap should be drawn to;
// NOTE: coords in canvas-space!
int xTranslate = ...
int yTranslate = ...
rotator.postTranslate(xTranslate, yTranslate);
canvas.drawBitmap(bitmap, rotator, paint);
This way the canvas stays directed as before, and you can do more stuff with your matrix like translating, scaling etc. and the matrix's content encapsulates the real meaning of your manipulation.
Edit: Eddie wanted to know around which point the rotation happens.
Edit: AndrewOrobator wanted to know how to set the canvas destination coords
Upvotes: 60