There is a statement in android canvas.drawBitmap(visiblePage, 0, 0, paint);
When I add canvas.rotate(90)
, there is no effect. But if I wri
Just be careful of Bitmap type from java platform call like from comm1x's and Gnzlt's answers, because it might return null. I think it is also more flexible if the parameter can be any Number and use infix for readability, depends on your coding style.
infix fun Bitmap.rotate(degrees: Number): Bitmap? {
return Bitmap.createBitmap(
this,
0,
0,
width,
height,
Matrix().apply { postRotate(degrees.toFloat()) },
true
)
}
How to use?
bitmap rotate 90
// or
bitmap.rotate(90)
If you rotate bitmap, 90 180 270 360 is ok but for other degrees canvas will draw bitmap with different size.
So,the best way is
canvas.rotate(degree,rotateCenterPoint.x,rotateCenterPoint.y);
canvas.drawBitmap(...);
canvas.rotate(-degree,rotateCenterPoint.x,rotateCenterPoint.y);//rotate back
Using Java createBitmap()
method you can pass the degrees.
Bitmap bInput /*your input bitmap*/, bOutput;
float degrees = 45; //rotation degree
Matrix matrix = new Matrix();
matrix.setRotate(degrees);
bOutput = Bitmap.createBitmap(bInput, 0, 0, bInput.getWidth(), bInput.getHeight(), matrix, true);
public static Bitmap RotateBitmap(Bitmap source, float angle)
{
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}
To get Bitmap from resources:
Bitmap source = BitmapFactory.decodeResource(this.getResources(), R.drawable.your_img);
Short extension for Kotlin
fun Bitmap.rotate(degrees: Float): Bitmap {
val matrix = Matrix().apply { postRotate(degrees) }
return Bitmap.createBitmap(this, 0, 0, width, height, matrix, true)
}
And usage:
val rotatedBitmap = bitmap.rotate(90f)
I would simplify comm1x's Kotlin extension function even more:
fun Bitmap.rotate(degrees: Float) =
Bitmap.createBitmap(this, 0, 0, width, height, Matrix().apply { postRotate(degrees) }, true)