Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate Bitmap on Android Canvas

Tags:

android

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);
  }

}
like image 803
fredley Avatar asked Aug 16 '10 18:08

fredley


2 Answers

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

like image 167
Bondax Avatar answered Nov 12 '22 20:11

Bondax


You just have to call

canvas.rotate(90) :) // 90 is degree.

like image 38
Romain Guy Avatar answered Nov 12 '22 18:11

Romain Guy