decades
decades

Reputation: 827

Android: Rotation of image around the center

I'm trying to rotate an image around the center. This works generally using RotateAnimation, but I want to have it a bit faster. I'm now using the SurfaceView pattern with a separate drawing thread.

This is code, which draws the bitmap correctly (depending on the outer "heading")

heading = angle in degrees, bitmap = the 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);

Drawback: The image is a circle and the code above produces visible aliasing effects...

The code below is also rotating the image, but while rotating (say from 0 to 45 degrees clockwise) the center of the new image moves bottom/right. I suppose, the eccentric effect is due to the enlarged width/height of the new image ?? However, this code doesn't produce aliasing, if filter=true is set. Is there a way to use code #1 but have sort of anti-aliasing or use code #2 but getting 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 result of the discussion in this thread the correct version of code #2 (anti-aliasing and correct rotation) would look like this (offset of 50,50 omitted):

        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.

Upvotes: 4

Views: 8880

Answers (1)

Unconn
Unconn

Reputation: 622

Find the center of the original image and for the new image and center using that:

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);

Upvotes: 1

Related Questions