Android围绕中心旋转位图而不调整大小
我正在努力围绕其中心绘制旋转位图并在不调整位图大小的情况下进行旋转.我正在通过游戏线程将我的所有精灵绘制到屏幕上,因此我正在寻找一种包含原始位图而不是画布的解决方案.
I'm struggling to draw a rotating bitmap around its center and do the rotating without resizing the bitmap. I'm drawing all my sprites to the screen via a game thread, so I'm looking for a solution that incorporates the original bitmap and not the canvas.
提前致谢.
到目前为止,这是我的代码,它围绕其中心旋转一个位图,然后调整它的大小.
This is my code so far, it turns a bitmap around its center, yet resizes it.
i = i + 2;
transform.postRotate(i, Assets.scoresScreen_LevelStar.getWidth()/2, Assets.scoresScreen_LevelStar.getHeight()/2);
Bitmap resizedBitmap = Bitmap.createBitmap(Assets.scoresScreen_LevelStar, 0, 0, Assets.scoresScreen_LevelStar.getWidth(), Assets.scoresScreen_LevelStar.getHeight(), transform, true);
game.getGraphics().getCanvasGameScreen().drawBitmap(resizedBitmap, null, this.levelStar.getHolderPolygons().get(0), null);
更新:
我注意到这并不像听起来那么容易.我的旋转代码不是问题.位图旋转,但 dst rect 也必须根据旋转角度增加/减少,否则 bimap 会显得更小,因为它被绘制到固定的 dst rect 中.所以我猜我必须开发一些方法来返回一个 dst rect.所以需要旋转位图而不出现调整大小的方法:
I've noticed this isn't as easy as it sounds. My rotating code is not the problem. The bitmap rotates, yet the dst rect will also have to increase/decrease depending on the angle of rotation, or else the bimap will appear smaller, since it's drawn into a fixed dst rect. So I'm guessing I'll have to develop some method that will return a dst rect. So the methods needed to rotate a bitmap without appeared resizing:
public static Bitmap rotateBitmap(Bitmap bitmap, int rotation) // I've got this method working
和
public static Rect rotateRect(Rect currentDst, int rotation) // Don't got this
我知道这需要一些数学(三角),有人愿意挑战吗?:P
I understand this will require some math (trig), anyone up for the challenge? :P
推荐答案
这对我有用!
我创建了一个返回矩阵的方法.该矩阵可用于以下绘制方法:
I created a method that returns a matrix. The matrix can be used in the following drawing method:
public void drawBitmap (Bitmap bitmap, Matrix matrix, Paint paint)
给你!(参数形状可以轻松替换,如果您愿意,请发表评论):
Here you go! (The parameter shape can be replaced with ease, if you would like that, just leave a comment):
public static Matrix rotateMatrix(Bitmap bitmap, Shape shape, int rotation) {
float scaleWidth = ((float) shape.getWidth()) / bitmap.getWidth();
float scaleHeight = ((float) shape.getHeight()) / bitmap.getHeight();
Matrix rotateMatrix = new Matrix();
rotateMatrix.postScale(scaleWidth, scaleHeight);
rotateMatrix.postRotate(rotation, shape.getWidth()/2, shape.getHeight()/2);
rotateMatrix.postTranslate(shape.getX(), shape.getY());
return rotateMatrix;
}
注意:如果您想要动画旋转,则必须每帧使用新值更新旋转参数,例如.1 然后 2 然后 3 ...
NB: If you want an animated rotation, the rotation parameter will have to be updated with new values every frame eg. 1 then 2 then 3 ...
相关文章