0

我正在尝试绘制由纹理打包器创建的精灵(一个大位图,其中包含每个精灵的宽度、高度、位置、纹理矩形等信息)目前尚不清楚如何绘制精灵以防它应该旋转 90 度。我尝试旋转画布但没有成功(精灵没有出现在正确的位置)

这就是我绘制常规(未旋转)精灵的方式:

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

使用旋转的精灵我旋转画布

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

并以与常规(未旋转)精灵相同的方式绘制精灵。但它出现在错误的位置。

有人可以帮助解决这个问题吗?

4

1 回答 1

0

我最终得到了旋转位图而不是画布。对我来说似乎更容易一些。

给定:textureRect - spritesheet 中的精灵矩形, spriteOffset - 精灵应该在画布上绘制的点,旋转 - 在我的例子中是 -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);

请注意,我将高度添加到 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);

事实上,三个 postTranslate 可以简化为一个,但我想将它们全部发布并附上评论以使其清楚。

于 2015-07-23T10:06:09.253 回答