【问题标题】:Issue rotating bitmap in Android在Android中发出旋转位图
【发布时间】:2011-11-09 22:19:52
【问题描述】:

我无法正确旋转位图。我有一个 SurfaceView,上面有多个位图。这些位图存在于数组列表中,并使用 for 循环为 onDraw 方法中的每个位图调用 canvas.drawBitmap。

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawColor(Color.BLACK);

    for (int i = 0; i < jumper.size(); i++) {
        canvas.drawBitmap(jumper.get(i).getGraphic(), jumper.get(i)
                .getCoordinates().getX(), jumper.get(i).getCoordinates()
                .getY(), null);
    }
}

我试图让用户选择一个特定的位图(许多位图之一),然后在用户在屏幕上拖动手指时让该位图旋转。所以这里是轮换代码。现在我只是使用默认的 android 图标 (72x72px) 存在于屏幕中心附近的某个随机位置。

private void rotateJumper(int direction) {
    Matrix matrix = new Matrix();
    Bitmap source = jumper.get(selectedJumperPos).getGraphic();
    matrix.postRotate(direction, source.getWidth() / 2, 
            source.getHeight() / 2);
    int x = 0;
    int y = 0;
    int width = 72;
    int height = 72;
    Bitmap tempBitmap = Bitmap.createBitmap(source, x, y, width, height,       
            matrix, true);
    jumper.get(selectedJumperPos).setGraphic(tempBitmap);
}

整数方向是 +1 或 -1,具体取决于手指拖动的方向。所以图像应该为每个 MotionEvent.ACTION_MOVE 事件旋转 1 度。

以下是问题:

  1. 图像不围绕图像中心旋转。 CW 以左下角为中心旋转。 CCW 以右上角为中心旋转。
  2. 由于不是围绕中心旋转,图像会在初始范围之外旋转并最终消失。
  3. 图像在旋转时变得模糊。

您能给我的任何帮助将不胜感激。

谢谢!

【问题讨论】:

    标签: android bitmap rotation


    【解决方案1】:

    使用矩阵将现有位图绘制到画布而不是创建新位图:

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawColor(Color.BLACK);
    
        for (int i = 0; i < jumper.size(); i++) {
            canvas.drawBitmap(jumper.get(i).getGraphic(), jumper.get(i).getMatrix(), null);
        }
    }
    
    private void rotateJumper(int direction) {
        Matrix matrix = jumper.get(selectedJumperPos).getMatrix();
        if(matrix == null) {
            matrix = new Matrix();
            matrix.setTranslate(jumper.get(...).getCoord...().getX(), jumper.get(..).getCoord...().getY());
            jumper.get(selectedJumperPos).setMatrix(matrix);
        }
        Bitmap source = jumper.get(selectedJumperPos).getGraphic();
        matrix.postRotate(direction, source.getWidth() / 2, 
                source.getHeight() / 2);
    
    }
    

    【讨论】:

    • 这行得通。进行了相当大的重新设计,但它奏效了。谢谢!
    • 不是每次发生旋转时都创建一个新的位图,而是在渲染过程中保留和使用矩阵。在 rotateJumper 中,我们仅在需要时初始化一个矩阵,然后围绕位图的中心旋转它。我们在绘制位图时在 onDraw 方法中使用矩阵 - 矩阵可以包含有关在画布上绘制位置(平移)、绘制大小(缩放)和旋转的数据。
    【解决方案2】:

    请原谅我的题外话,但你的 for 循环引起了我的注意。或许可以写成“更易读”的格式;

    for (YourJumperItem item : jumper) {
        canvas.drawBitmap(
            item.getGraphic(), item.getCoordinates().getX(),
            item.getCoordinates().getY(), null );
    }
    

    YourJumperItem 是您的 jumper -array 包含的类类型。不幸的是,关于旋转位图不能多说,我只是在推广这种方便的 for -loops 编写方式。

    【讨论】:

      猜你喜欢
      • 2015-07-11
      • 1970-01-01
      • 1970-01-01
      • 2012-05-14
      • 2012-10-17
      • 1970-01-01
      • 1970-01-01
      • 2011-08-31
      • 1970-01-01
      相关资源
      最近更新 更多