Android: rotate the image around the center

I am trying to rotate the image around the center. This works mainly with RotateAnimation, but I want it to be a little faster. Now I am using a SurfaceView template with a separate drawing stream.

This is the code that correctly draws a bitmap (depending on the external "header")

header = angle in degrees, bitmap = bitmap, w = width of the bitmap, h = height of the bitmap.

Matrix m = new Matrix(); m.preRotate(heading, w/2, h/2); m.setTranslate(50,50); canvas.drawBitmap(bitmap, m, null); 

Disadvantage: the image is a circle, and the code above creates visible smoothing effects ...

The code below also rotates the image, but when you rotate (for example, from 0 to 45 degrees clockwise), the center of the new image moves right / right. I suppose the eccentric effect is due to the increased width / height of the new image? However, this code does not create aliases if filter = true is set. Is there a way to use code # 1, but look like anti-aliasing or use code # 2, but get rid of the center movement?

  Matrix m = new Matrix(); m.preRotate(heading, w/2, h/2); m.setTranslate(50,50); Bitmap rbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, m, true); canvas.drawBitmap(rbmp, 50, 50, null); 

UPDATE: As a result of the discussion in this thread, the correct version of code # 2 (smoothing and proper rotation) will look like this (offset 50.50 is skipped):

  Matrix m = new Matrix(); m.setRotate(heading, w/2, h/2); Bitmap rbpm = Bitmap.createBitmap(bitmap, 0, 0, w, h, m, true); canvas.drawBitmap(rbpm, (w - rbpm.getWidth())/2, (h - rbpm.getHeight())/2, null); 

Thanks.

+4
source share
1 answer

Find the center of the original image, and use this for the new image and center:

 Matrix minMatrix = new Matrix(); //height and width are set earlier. Bitmap minBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas minCanvas = new Canvas(minBitmap); int minwidth = bitmapMin.getWidth(); int minheight = bitmapMin.getHeight(); int centrex = minwidth/2; int centrey = minheight/2; minMatrix.setRotate(mindegrees, centrex, centrey); Bitmap newmin = Bitmap.createBitmap(minBitmap, 0, 0, (int) minwidth, (int) minheight, minMatrix, true); minCanvas.drawBitmap(newmin, (centrex - newmin.getWidth()/2), (centrey - newmin.getHeight()/2), null); minCanvas.setBitmap(minBitmap); 
+1
source

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


All Articles