[android] Android: How to rotate a bitmap on a center point

I've been looking for over a day for a solution to this problem but nothing helps, even the answers here. Documentation doesn't explain anything too.

I am simply trying to get a rotation in the direction of another object. The problem is that the bitmap is not rotated around a fixed point, but rather around the bitmaps (0,0).

Here is the code I am having troubles with:

  Matrix mtx = new Matrix();
  mtx.reset();
  mtx.preTranslate(-centerX, -centerY);
  mtx.setRotate((float)direction, -centerX, -centerY);
  mtx.postTranslate(pivotX, pivotY);
  Bitmap rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0, spriteWidth, spriteHeight, mtx, true);
  this.bitmap = rotatedBMP;

The weird part is, it doesn't matter how I change the values within pre/postTranslate() and the float arguments in setRotation(). Can someone please help and push me in the right direction? :)

This question is related to android matrix bitmap center image-rotation

The answer is


Edited: optimized code.

public static Bitmap RotateBitmap(Bitmap source, float angle)
{
      Matrix matrix = new Matrix();
      matrix.postRotate(angle);
      return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}

To get Bitmap from resources:

Bitmap source = BitmapFactory.decodeResource(this.getResources(), R.drawable.your_img);

You can also rotate the ImageView using a RotateAnimation:

RotateAnimation rotateAnimation = new RotateAnimation(from, to,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                0.5f);
rotateAnimation.setInterpolator(new LinearInterpolator());
rotateAnimation.setDuration(ANIMATION_DURATION);
rotateAnimation.setFillAfter(true);

imageView.startAnimation(rotateAnimation);

You can use something like following:


Matrix matrix = new Matrix();
matrix.setRotate(mRotation,source.getWidth()/2,source.getHeight()/2);
RectF rectF = new RectF(0, 0, source.getWidth(), source.getHeight());
matrix.mapRect(rectF);
Bitmap targetBitmap = Bitmap.createBitmap(rectF.width(), rectF.height(), config);
Canvas canvas = new Canvas(targetBitmap);
canvas.drawBitmap(source, matrix, new Paint());


I hope the following sequence of code will help you:

Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight, config);
Canvas canvas = new Canvas(targetBitmap);
Matrix matrix = new Matrix();
matrix.setRotate(mRotation,source.getWidth()/2,source.getHeight()/2);
canvas.drawBitmap(source, matrix, new Paint());

If you check the following method from ~frameworks\base\graphics\java\android\graphics\Bitmap.java

public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height,
        Matrix m, boolean filter)

this would explain what it does with rotation and translate.


I used this configurations and still have the problem of pixelization :

Bitmap bmpOriginal = BitmapFactory.decodeResource(this.getResources(), R.drawable.map_pin);
        Bitmap targetBitmap = Bitmap.createBitmap((bmpOriginal.getWidth()),
                (bmpOriginal.getHeight()), 
                Bitmap.Config.ARGB_8888);
        Paint p = new Paint();
        p.setAntiAlias(true);

        Matrix matrix = new Matrix();       
        matrix.setRotate((float) lock.getDirection(),(float) (bmpOriginal.getWidth()/2),
                (float)(bmpOriginal.getHeight()/2));

        RectF rectF = new RectF(0, 0, bmpOriginal.getWidth(), bmpOriginal.getHeight());
        matrix.mapRect(rectF);

        targetBitmap = Bitmap.createBitmap((int)rectF.width(), (int)rectF.height(), Bitmap.Config.ARGB_8888);


        Canvas tempCanvas = new Canvas(targetBitmap); 
        tempCanvas.drawBitmap(bmpOriginal, matrix, p);

I came back to this problem now that we are finalizing the game and I just thought to post what worked for me.

This is the method for rotating the Matrix:

this.matrix.reset();
this.matrix.setTranslate(this.floatXpos, this.floatYpos);
this.matrix.postRotate((float)this.direction, this.getCenterX(), this.getCenterY()); 

(this.getCenterX() is basically the bitmaps X position + the bitmaps width / 2)

And the method for Drawing the bitmap (called via a RenderManager Class):

canvas.drawBitmap(this.bitmap, this.matrix, null);

So it is prettey straight forward but I find it abit strange that I couldn't get it to work by setRotate followed by postTranslate. Maybe some knows why this doesn't work? Now all the bitmaps rotate properly but it is not without some minor decrease in bitmap quality :/

Anyways, thanks for your help!


Look at the sample from Google called Lunar Lander, the ship image there is rotated dynamically.

Lunar Lander code sample


matrix.reset();
matrix.setTranslate( anchor.x, anchor.y );
matrix.postRotate((float) rotation , 0,0);
matrix.postTranslate(positionOfAnchor.x, positionOfAnchor.x);
c.drawBitmap(bitmap, matrix, null); 

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to matrix

How to get element-wise matrix multiplication (Hadamard product) in numpy? How can I plot a confusion matrix? Error: stray '\240' in program What does the error "arguments imply differing number of rows: x, y" mean? How to input matrix (2D list) in Python? Difference between numpy.array shape (R, 1) and (R,) Counting the number of non-NaN elements in a numpy ndarray in Python Inverse of a matrix using numpy How to create an empty matrix in R? numpy matrix vector multiplication

Examples related to bitmap

How to solve java.lang.OutOfMemoryError trouble in Android Save and retrieve image (binary) from SQL Server using Entity Framework 6 How to create bitmap from byte array? Fastest way to convert Image to Byte array How to save a bitmap on internal storage Android set bitmap to Imageview Save bitmap to file function How to resize Image in Android? Android Bitmap to Base64 String Android load from URL to Bitmap

Examples related to center

Center Plot title in ggplot2 How to make a <div> or <a href="#"> to align center How to center an unordered list? Bootstrap 3 modal vertical position center How to align title at center of ActionBar in default theme(Theme.Holo.Light) How to center absolute div horizontally using CSS? Resize to fit image in div, and center horizontally and vertically Center fixed div with dynamic width (CSS) RelativeLayout center vertical Center button under form in bootstrap

Examples related to image-rotation

How to rotate the background image in the container? Android: How to rotate a bitmap on a center point