Bitmap Rotates the bitmap by the specified degree. - Android Graphics

Android examples for Graphics:Bitmap Rotate

Description

Bitmap Rotates the bitmap by the specified degree.

Demo Code


//package com.book2s;
import android.graphics.Bitmap;

import android.graphics.Matrix;

public class Main {

    public static Bitmap rotate(Bitmap bitmap, int degree) {
        return rotateAndMirror(bitmap, degree, false);
    }/*from w  ww. j av  a  2 s.  com*/

    public static Bitmap rotateAndMirror(Bitmap bitmap, int degree,
            boolean isMirror) throws OutOfMemoryError {

        if ((degree != 0 || isMirror) && bitmap != null) {
            Matrix m = new Matrix();
            m.setRotate(degree, (float) bitmap.getWidth() / 2,
                    (float) bitmap.getHeight() / 2);

            if (isMirror) {
                m.postScale(-1, 1);
                degree = (degree + 360) % 360;
                if (degree == 0 || degree == 180) {
                    m.postTranslate((float) bitmap.getWidth(), 0);
                } else if (degree == 90 || degree == 270) {
                    m.postTranslate((float) bitmap.getHeight(), 0);
                } else {
                    throw new IllegalArgumentException("Invalid degrees="
                            + degree);
                }
            }

            Bitmap bitmap2 = Bitmap.createBitmap(bitmap, 0, 0,
                    bitmap.getWidth(), bitmap.getHeight(), m, true);
            if (bitmap != bitmap2) {
                bitmap.recycle();
                System.gc();
                bitmap = bitmap2;
            }
        }
        return bitmap;
    }
}

Related Tutorials