【问题标题】:Bitmap - Matrix operations (scale, rotate and translate)位图 - 矩阵操作(缩放、旋转和平移)
【发布时间】:2013-08-10 14:25:23
【问题描述】:

我需要一些关于矩阵运算的帮助。我想要实现的是:

  • 按比例缩小
  • 移动到特定位置
  • 旋转一定角度(在位图的中心)

我的代码目前如下所示:

            Matrix matrix = new Matrix();
            matrix.preRotate(mShip.getRotation(), mShip.getX() + mShip.getCurrentBitmap().getWidth()/2f, mShip.getY()  + mShip.getCurrentBitmap().getHeight()/2f);
            matrix.setScale((1.0f * mShip.getWidth() / mShip.getCurrentBitmap().getWidth()), (1.0f * mShip.getHeight() / mShip.getCurrentBitmap().getHeight()));
            matrix.postTranslate(mShip.getX(), mShip.getY());
            mCanvas.drawBitmap(mShip.getCurrentBitmap(), matrix, mBasicPaint);

但是旋转的中心错误,我不知道如何解决这个问题 - 我已经在 SO 上环顾四周,但只发现了类似的问题,没有解决方案。 我认为我可能必须将其中一个操作应用于另一个值,因为它们是按顺序执行的,但我不知道该怎么做。

【问题讨论】:

    标签: android matrix android-canvas


    【解决方案1】:

    试试这个代码:

    Matrix matrix = new Matrix();
    matrix.setTranslate(-mShip.getCurrentBitmap().getWidth()/2f, -mShip.getCurrentBitmap().getHeight()/2f);
    matrix.postRotate(mShip.getRotation());
    matrix.postTranslate(mShip.getX(), mShip.getY());
    matrix.postScale((1.0f * mShip.getWidth() / mShip.getCurrentBitmap().getWidth()), (1.0f * mShip.getHeight() / mShip.getCurrentBitmap().getHeight()), mShip.getX(), mShip.getY());
    

    【讨论】:

    • 谢谢,但现在翻译在顶部和后面太远了。我通过将 postTranslate 更改为 postTranslate(getX() + getWidth()/2f, getY() + getHeight()/2f) 来修复它,现在它可以工作了!非常感谢你。你能给我一个提示/解释为什么需要这两种翻译吗?
    • 首先平移需要将图像中心移动到 (0,0),所以它可以围绕它的中心旋转。完成此操作后,可以将其移动到目标点并进行缩放。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-22
    相关资源
    最近更新 更多