简体   繁体   English

如何在画布上绘制旋转了某个值的位图的一部分

[英]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. 我正在尝试绘制由纹理打包器创建的子画面(一个大位图,其中包含每个子画面的宽度,高度,位置,纹理矩形等信息)目前尚不清楚如何绘制子画面以防应旋转90度。 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 给定:textureRect-spritesheet中的sprite rect,spriteOffset-在画布上绘制sprite的位置,旋转-在我的情况下为-90度

//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. 请注意,我在X上增加了高度,在Y上增加了宽度。这不是打印错误,这是有意的,因为位图是旋转的。

//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. 实际上,可以将三个postTranslate简化为一个,但是我想将所有这些都添加评论以使其清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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