While it seems like an incredibly common piece of functionality, there’s no obvious rotateBitmap
method included with the Android SDK.
However, it’s trivial to write (or copy and paste) your own method, similar to the one below:
fun rotateBitmap(source: Bitmap, degrees: Float): Bitmap {
val matrix = Matrix()
matrix.postRotate(degrees)
return Bitmap.createBitmap(
source, 0, 0, source.width, source.height, matrix, true
)
}
What’s happening here?
-
First, we’re creating a
Matrix
object, which is part of theandroid.graphics
package. AMatrix
holds a grid of transformation coordinates that can be applied to bitmaps and other graphics. -
Rather than populating the grid manually, it has the method
postRotate
which accepts adegrees
parameter. -
A second bitmap is created using the static
createBitmap
method, passing in the originalsource
bitmap along with ourMatrix
.
Since we want to rotate the entire bitmap, the 2nd and 3rd parameters can be set as 0
, and the 4th and 5th parameters should be the source image width and height.
Usage
Typically, rotating an image would be used in more than one place within the application, so I would suggest putting the image-rotation logic into its own utility class.
object ImageRotationUtility {
fun rotateBitmap(source: Bitmap, angle: Float): Bitmap {
val matrix = Matrix()
matrix.postRotate(angle)
return Bitmap.createBitmap(
source, 0, 0, source.width, source.height, matrix, true
)
}
}
Then to rotate an image by 90 degrees:
val rotatedBitmap = ImageRotationUtility.rotateBitmap(source, 90f)