I’m learning a lot from my first experience with Android development, and find the SDK and APIs pretty easy to work with. I’ve found you can achieve some pretty impressive results with relatively few lines of code but sometimes I end up thinking a problem is harder than it actually turns out to be. Rotating bitmaps is one of them.
I have a need in my android app to pull an image from a web service, rotate it 90 degress, scale it and then display it in the centre of the screen. This is what I did to achive that goal.
// Get the image we want to work with from a URL Bitmap myBitmap = BitmapFactory.decodeStream(downloadImageFromWeb()); // or just load a resource from the res/drawable directory: Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.android1); // find the width and height of the screen: Display d = getWindowManager().getDefaultDisplay(); int x = d.getWidth(); int y = d.getHeight(); // get a reference to the ImageView component that will display the image: ImageView img1 = (ImageView)findViewById(R.id.img1); // scale it to fit the screen, x and y swapped because my image is wider than it is tall Bitmap scaledBitmap = Bitmap.createScaledBitmap(myBitmap, y, x, true); // create a matrix object Matrix matrix = new Matrix(); matrix.postRotate(-90); // anti-clockwise by 90 degrees // create a new bitmap from the original using the matrix to transform the result Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap , 0, 0, scaledBitmap .getWidth(), scaledBitmap .getHeight(), matrix, true); // display the rotated bitmap img1.setImageBitmap(rotatedBitmap);
The key to the rotation is the Matrix object. According to the Android documentation “The Matrix class holds a 3×3 matrix for transforming coordinates”. And er, that’s it. The actual rotation is applied using the createBitmap overload that takes the bitmap to transform and the matrix instance that has had the postRotate method called on it. Buried in the middle is a call to scale the bitmap but that’s not the focus here.
Having written the code, you of course need an ImageView defined in your layout xml file which we can call setImageBitmap on as shown above. This is the layout I used.
<ImageView android:background="#ffffffff" android:id="@+id/img1" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_gravity="center" android:maxWidth="250dip" android:maxHeight="250dip" android:adjustViewBounds="true" />
Note that the maxWidth and maxHeight properties ensure that I don’t scale the image up too much (I’m still experimenting as to what looks good across different screen sizes) though they don’t seem to have any effect unless you include the adjustViewBounds=”true” attribute as well.
So, in the end, rotating a bitmap is trivial and nowhere near as complex as I originally assumed it might be – a pattern I’m starting to see repeated throughout my Android development experience.