Android旋转位图而不改变大小

6
我在尝试绘制一个围绕其中心旋转的位图,而且不改变位图的大小。我通过游戏线程将所有精灵绘制到屏幕上,所以我正在寻找一种解决方案,可以使用原始位图而不是画布。
以下是我的代码,它可以使位图围绕其中心旋转,但同时也改变了其大小。
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);

更新:

我注意到这并不像听起来那么容易。我的旋转代码并不是问题所在。位图旋转了,但是目标矩形也必须根据旋转角度增加/减小,否则位图将会显得更小,因为它被绘制到一个固定的目标矩形中。

所以我想我需要开发一些方法来返回目标矩形。要旋转位图而不出现大小调整,需要以下方法:

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


你目前尝试了什么?你能提供一些未成功的例子吗? - nicholas.hauschild
直接使用Android还是Cocos2d-x? - Fallenreaper
更新了带有代码的问题,@Fallenreaper,我在使用自己的GE,所以是直接使用Android。 - Luke Taylor
代码看起来正确。问题可能出在绘图时。 - Ron
2个回答

8

您应该使用Matrix类来绘制位图。以下是一个非常基本的想法,假设您想要旋转“Ship”类中的图像。您在update方法中更新当前位置矩阵。在onDraw()中,使用新更新的位置矩阵绘制位图。这将绘制旋转的位图而不重塑它。

public class Ship extends View {

    private float x, y;
    private int rotation;
    private Matrix position;    
    private Bitmap bitmap;

    ...

    @Override
    public void onDraw(Canvas canvas) {
        // Draw the Bitmap using the current position
        canvas.drawBitmap(bitmap, position, null);
    }

    public void update() {
        // Generate a new matrix based off of the current rotation and x and y coordinates.
        Matrix m = new Matrix();
        m.postRotate(rotation, bitmap.getWidth()/2, bitmap.getHeight()/2);
        m.postTranslate(x, y);

        // Set the current position to the updated rotation
        position.set(m);

        rotation += 2;
    }

    ....

}

希望这有帮助! 还要记住,在游戏循环中生成新的"Bitmap"对象会占用大量资源。

你能否重写一下,让我能够调用一个名为rotateBitmap(Bitmap bitmap, int rotation)的静态方法,并返回一个旋转后的Bitmap对象? - Luke Taylor
该方法会更改您传入的位图,因此您的私有变量“private Bitmap bitmap;”不会被旋转。只需执行“return bitmap;”并更改方法签名即可。 - Aziz

0

这对我有用!

我创建了一个返回矩阵的方法。该矩阵可以在以下绘图方法中使用:

public void drawBitmap (Bitmap bitmap, Matrix matrix, Paint paint)

这是您需要的!(如果您想要替换参数形状,可以轻松地进行更改,请在评论中留言):

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...。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接