简体   繁体   中英

How to draw a part of a bitmap rotated by a certain value on a canvas

I'm trying to draw sprites created by texture packer (one big bitmap with informations such as width, height, position, texture rect for each sprite) It's not clear how to draw a sprite in case that it should be rotated by 90 degrees. I tried rotating canvas but I didn't success (sprite didn't appeared in right position)

This is how I draw regular (not rotated) sprites:

Rect srcRect = <a rect in the big bitmap> (for example left=0, top=0, right=100, bottom=80)
Rect destRect = new Rect(spriteOffsetX, spriteOffsetY, spriteOffset.x + spriteWidth, spriteOffset.y + spriteHeight);
canvas.drawBitmap(bitmap, srcRect, destRect, null);

With rotated sprites I rotate canvas

canvas.rotate(-90f, canvas.getWidth() / 2.0f, canvas.getHeight() / 2.0f);

and draw sprite the same way as regular (not rotated) sprite. But it appears in wrong position.

Could somebody help with this problem?

I ended up with rotating bitmap instead of canvas. It appears to be a little easier for me.

Given: textureRect - sprite rect in spritesheet, spriteOffset - point where the sprite should be drawn on a canvas, rotation - in my case it's -90 degree

//this code is required because we need to clip the rest of bitmap
//we only need a sprite to be drawn
destRect.left = spriteOffset.x;
destRect.top = spriteOffset.y;
destRect.right = spriteOffset.x + textureRect.height();
destRect.bottom = spriteOffset.y + textureRect.width();
canvas.clipRect(destRect);

Note that I add height to X and width to Y. It's not misprint, it's intentional because bitmap is rotated.

//rotate, after this the bitmap will be above 0,0
matrix.postRotate(-90);
//move it so that the bitmap will be in 0,0 i.e. right left corner of the bitmap
//will be in left top corner if we draw the bitmap right now
matrix.postTranslate(0.0f, imageWidth);
//move so that sprite we need to draw will be in 0,0
matrix.postTranslate(-textureRect.top, -(imageWidth - textureRect.right));
//move again to final position
matrix.postTranslate(spriteOffset.x, spriteOffset.y);

In fact three postTranslate could be simplified into one but I wanted to post all of them with commentary to make it clear.

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