如何在不创建新位图的情况下旋转位图?

bir*_*rdy 6 java android image bitmap rotation

我正在使用它Bitmap从现有的旋转:

private Bitmap getRotatedBitmap(Bitmap bitmap, int angle) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Matrix mtx = new Matrix();
        mtx.postRotate(angle);
        return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
    }
Run Code Online (Sandbox Code Playgroud)

是否可以在不创建新位图的情况下完成?

我试图用以下方法重绘相同的可变图像Canvas:

Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight, config);
Canvas canvas = new Canvas(targetBitmap);
Matrix matrix = new Matrix();
matrix.setRotate(mRotation,source.getWidth()/2,source.getHeight()/2);
canvas.drawBitmap(targetBitmap, matrix, new Paint());
Run Code Online (Sandbox Code Playgroud)

但这种方法刚刚导致位图损坏.那么有没有可能实现它?

Ron*_*nie 1

这是画布上最简单的旋转代码,无需创建新的位图

canvas.save(); //save the position of the canvas
canvas.rotate(angle, X + (imageW / 2), Y + (imageH / 2)); //rotate the canvas
canvas.drawBitmap(imageBmp, X, Y, null); //draw the image on the rotated canvas
canvas.restore();  // restore the canvas position.
Run Code Online (Sandbox Code Playgroud)

  • 它不会旋转位图本身,而只是将其旋转绘制在视图内。我想要的是旋转位图并保存它。 (5认同)