简体   繁体   中英

How to rotate bitmap around center point using canvas?

I have a bitmap and I want to create a new bitmap obtained by the first rotated around its center. Actually I use this code but it does not work.

Bitmap source = ((BitmapDrawable)r.getDrawable(R.drawable.rectangle)).getBitmap();

int targetWidth = (int)(mWidth * Math.sin(rotationAngle) + mHeight * Math.cos(rotationAngle));
int targetHeight = (int)(mWidth * Math.cos(rotationAngle) + mHeight * Math.sin(rotationAngle));

Bitmap target = Bitmap.createBitmap(targetWidth, targetHeight, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(target);
Matrix m = new Matrix();
m.setRotate(rotationAngle, targetWidth/2f, targetHeight/2f);
c.drawBitmap(source, m, null);

I also tried this code but it doesn't help.

Bitmap source = ((BitmapDrawable)r.getDrawable(R.drawable.rectangle)).getBitmap();

int targetWidth = (int)(mWidth * Math.sin(rotationAngle) + mHeight * Math.cos(rotationAngle));
int targetHeight = (int)(mWidth * Math.cos(rotationAngle) + mHeight * Math.sin(rotationAngle));

Bitmap target = Bitmap.createBitmap(targetWidth, targetHeight, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(target);
c.rotate(rotationAngle, targetWidth/2f, targetHeight/2f);
c.drawBitmap(temp, 0, 0, null);

In this case the rotate command(but the same happens with the scale command) called on the canvas is completely ignored for any parameter. I also tried to use:

c.drawColor(Color.BLACK)

instead of

c.drawBitmap(temp, 0, 0, null);

to paint all the canvas and it confirms that the commands are ignored.

Try this:

Canvas c = new Canvas(target);

c.rotate(rotationAngle, centerX, centerY);

c.drawBitmap(source, null);

Hope this helps :)

int count = canvas.save();
canvas.rotate(rotationAngle, centerX, centerY);
c.drawBitmap(source, null);
canvas.restoreToCount(count);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM