Android How to - Rotate Bitmap








Question

We would like to know how to rotate Bitmap.

Answer

/*ww w.  j  a  v a  2  s.c o  m*/
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;

public class Main {
    public static Bitmap rotate(Bitmap bitmap, int rotation) {

        int targetWidth = bitmap.getWidth();
        int targetHeight = bitmap.getHeight();

        if (rotation == 90 || rotation == 270) {
            targetHeight = bitmap.getWidth();
            targetWidth = bitmap.getHeight();
        }

        Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight,
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(targetBitmap);
        Matrix matrix = new Matrix();
        matrix.setRotate(rotation, bitmap.getWidth() / 2, bitmap.getHeight() / 2);
        canvas.drawBitmap(bitmap, matrix, new Paint());

        bitmap.recycle();
        return targetBitmap;
    }
}