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

时间:2015-07-20 16:22:20

标签: android android-canvas texturepacker

我试图绘制由纹理打包器创建的精灵(一个大位图,其中包含每个精灵的宽度,高度,位置,纹理矩形等信息) 如果它应该旋转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);

并以与常规(非旋转)精灵相同的方式绘制精灵。但它似乎处于错误的位置。

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

1 个答案:

答案 0 :(得分:0)

我最终使用旋转位图而不是画布。对我来说似乎有点容易。

给定: textureRect - spritesheet中的sprite rect, 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可以简化为一个,但我想用评论发布所有帖子,以便明确。