Image rotating in Android

There is an easy way for image rotating in Android from code. I am going to show example.
Here I will use application’s icon as image and Matrix class.
Example:

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ImageView.ScaleType;

/**
 * This Activity shows how to rotate an image (Bitmap) using Matrix class
 * @author FaYnaSoft Labs
 */
public class Main extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout linearLayout = new LinearLayout(this);

		Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);

		int width = bitmap.getWidth();
		int height = bitmap.getHeight();

		Matrix matrix = new Matrix();
		matrix.postRotate(90);

		Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width,
				height, matrix, true);
		BitmapDrawable bmd = new BitmapDrawable(rotatedBitmap);

		ImageView imageView = new ImageView(this);
		imageView.setImageDrawable(bmd);
		imageView.setScaleType(ScaleType.CENTER);

		linearLayout.addView(imageView, new LinearLayout.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		setContentView(linearLayout);
    }
}

That’s all.
Main methods are:

matrix.postRotate(90);

and

Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);

As you can see it is simple.

Download code from this article.

Share

Leave a Reply

  

  

  

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

A sample text widget

Etiam pulvinar consectetur dolor sed malesuada. Ut convallis euismod dolor nec pretium. Nunc ut tristique massa.

Nam sodales mi vitae dolor ullamcorper et vulputate enim accumsan. Morbi orci magna, tincidunt vitae molestie nec, molestie at mi. Nulla nulla lorem, suscipit in posuere in, interdum non magna.