How to rotate a bitmap without creating a new one?

I use this to rotate a Bitmap from an existing one:

 private Bitmap getRotatedBitmap(Bitmap bitmap, int angle) { int w = bitmap.getWidth(); int h = bitmap.getHeight(); Matrix mtx = new Matrix(); mtx.postRotate(angle); return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true); } 

Can this be done without creating a new bitmap?

I tried to redraw the same mutable image using Canvas :

 Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight, config); Canvas canvas = new Canvas(targetBitmap); Matrix matrix = new Matrix(); matrix.setRotate(mRotation,source.getWidth()/2,source.getHeight()/2); canvas.drawBitmap(targetBitmap, matrix, new Paint()); 

but this approach has just damaged the bitmap. So are there any opportunities to achieve this?

+6
source share
1 answer

This is the simplest rotation on the canvas, without creating a new bitmap

 canvas.save(); //save the position of the canvas canvas.rotate(angle, X + (imageW / 2), Y + (imageH / 2)); //rotate the canvas canvas.drawBitmap(imageBmp, X, Y, null); //draw the image on the rotated canvas canvas.restore(); // restore the canvas position. 
0
source

Source: https://habr.com/ru/post/925923/


All Articles