Skip to content

Instantly share code, notes, and snippets.

@codeswimmer
Created March 7, 2011 17:25
Show Gist options
  • Save codeswimmer/858833 to your computer and use it in GitHub Desktop.
Save codeswimmer/858833 to your computer and use it in GitHub Desktop.
Android: rotate a bitmap
public Bitmap rotateBitmap(Bitmap original, float degrees) {
int width = original.getWidth();
int height = original.getHeight();
Matrix matrix = new Matrix();
matrix.preRotate(degrees);
Bitmap rotatedBitmap = Bitmap.createBitmap(original, 0, 0, width, height, matrix, true);
Canvas canvas = new Canvas(rotatedBitmap);
canvas.drawBitmap(original, 5.0f, 0.0f, null);
return rotatedBitmap;
}
@hendrawd
Copy link

hendrawd commented Apr 2, 2019

Bitmap.createBitmap is java call and might be null. And I think we can use Number for parameter and infix for readability

infix fun Bitmap.rotate(degrees: Number): Bitmap? {
    return Bitmap.createBitmap(
        this,
        0,
        0,
        width,
        height,
        Matrix().apply { postRotate(degrees.toFloat()) },
        true
    )
}

Usage

bitmap rotate 90

@wei-spring
Copy link

great !

@zartilas
Copy link

To understand, this piece of code will rotate my photo to the right position or I choose how much and where it will rotate. Thank you.

@donyor-02
Copy link

Thank you, nice code !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment