繁体   English   中英

Android在中心周围旋转位图而不调整大小

[英]Android rotate bitmap around center without resizing

我正在努力在其中心周围绘制一个旋转位图,并在不调整位图大小的情况下进行旋转。 我正在通过游戏线程将所有精灵绘制到屏幕上,所以我正在寻找一种包含原始位图而不是画布的解决方案。

提前致谢。

到目前为止,这是我的代码,它围绕其中心转换位图,然后调整它的大小。

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的方法。 所以旋转位图所需的方法没有出现调整大小:

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

您应该使用Matrix类绘制位图。 下面是一个非常基本的想法,假设您想要在“Ship”类中旋转图像。 您在update方法中更新当前位置Matrix。 在onDraw()中,您使用新更新的位置Matrix绘制位图。 这将绘制旋转的位图而不调整其大小。

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对象将是资源密集型的。

这对我有用!

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

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

暂无
暂无

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

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