0

I have tried several hours to rotate a bitmap with no success. I have read numerous articles about this subject on this web site and it seems the prefered solution involves creating a temporary canvas. Well I did this and I still do not see a roated bitmap.

My bitmap is a 40x40 blue square and I am trying to rotate it 45 degrees. Thats not asking for much is it? When the code runs, the bitmap that appears on the screen is the non-rotated original. ( I have also tried a translate with no success as well)

Here is my code:

// Load the bitmap resource
   fillBMP2 = BitmapFactory.decodeResource(context.getResources(), R.drawable.test1);
   // Copy to a mutable bitmap
   mb = fillBMP2.copy(Bitmap.Config.ARGB_8888, true);
   // Create canvas to draw to
   Canvas offscreenCanvas = new Canvas (mb);
   // Create Matrix so I can rotate it 
   Matrix matrix = new Matrix();
   matrix.setRotate (45); 
   offscreenCanvas.setMatrix (matrix);
   // Send the contents of the canvas into a bitmap
   offscreenCanvas.setBitmap(mb);

Later in an OnDraw I do the following:

canvas.drawBitmap(mb, 200, 200, null);

Any ideas what I am doing wrong? Seems like it should work.

Thanks

Jack
  • 241
  • 4
  • 12
  • I'm not too familiar with ``Canvas`` but I'm assuming you should alter ``canvas.setMatrix(Matrix)`` before rendering instead of using ``offscreenCanvas``. – harism Aug 28 '12 at 22:14
  • check this SOF answer http://stackoverflow.com/a/12044717/886001 – ColdFire Aug 29 '12 at 00:32

3 Answers3

1

Try using this

Matrix matrix = new Matrix();
matrix.setRotate(15);
canvas.drawBitmap(bmp, matrix, paint);

setRotation method takes in a float representing the degrees of rotation.

Numair
  • 1,062
  • 1
  • 20
  • 41
  • I tried making the rotation angle a float with no results. My call to canvas.drawBitmap in OnDraw is simply to test the results of the bitmap rotation. – Jack Aug 28 '12 at 22:23
1

Try this...

    Matrix matrix = new Matrix();

    float px = 200;

    float py = 200;

    matrix.postTranslate(-bitmap.getWidth()/2, -bitmap.getWidth()/2);

    matrix.postRotate(45);

    matrix.postTranslate(px, py);

    canvas.drawBitmap(bitmap, matrix, paint);
Mani
  • 231
  • 1
  • 14
0

You definitely want to use transformations: check out this link.

Basically it's this:

// save the canvas
ctx.save();

// move origin to center
ctx.translate(x,y); 

// rotate
ctx.rotate(angle * (Math.PI / 180));

// draw image
ctx.drawImage(image, x, y, w, h, .w/2, h/2, w, h);

// restore
ctx.restore();
Jarrod
  • 9,349
  • 5
  • 58
  • 73