为什么有时Bitmaps是相同的对象?

ska*_*red 5 java android bitmap matrix

在我的代码中,我正在做这样的事情:

public void doStuff() {
    Bitmap scaledBitmap = decodeFileAndResize(captureFile);
    saveResizedAndCompressedBitmap(scaledBitmap);

    Bitmap rotatedBitmap = convertToRotatedBitmap(scaledBitmap);
    driverPhoto.setImageBitmap(rotatedBitmap);

    if (rotatedBitmap != scaledBitmap) {
        scaledBitmap.recycle();
        scaledBitmap = null;
        System.gc();
    }
}

private Bitmap convertToRotatedBitmap(Bitmap scaledBitmap) throws IOException {
    ExifInterface exifInterface = new ExifInterface(getCaptureFilePath());
    int exifOrientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
    float orientationDegree = getRotationDegree(exifOrientation);
    Matrix rotateMatrix = new Matrix();
    rotateMatrix.postRotate(orientationDegree);

    return Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), rotateMatrix, true);
}
Run Code Online (Sandbox Code Playgroud)

一切正常,但是当我发表评论时,if (rotatedBitmap != scaledBitmap) {我有一个关于使用再生Bitmap的错误.

Android是否会在每次Bitmap.createBitmap调用时创建新的Bitmap ,如何避免位图之间的比较?

Sun*_*hoo 3

createBitmap(Bitmap source, int x, int y, int width, int height, Matrix m, boolean filter) 从源位图的子集返回一个不可变的位图,并通过可选矩阵进行转换。

如果满足以下所有条件,则创建 BitMap 方法将返回与传递的 Bitmap 方法相同的值

  • 如果您的 sourceBitmap 是不可变的并且
  • 像素从 0,0 xy 开始并且
  • 预期的宽度和高度与原始宽度和高度相同并且
  • 矩阵为空

在android源代码中,有些内容是这样写的

if (!source.isMutable() && x == 0 && y == 0
                && width == source.getWidth() && height == source.getHeight()
                && (m == null || m.isIdentity())) {
            return source;
    }
Run Code Online (Sandbox Code Playgroud)

从这里查看 BitMap.java 的源代码

http://www.netmite.com/android/mydroid/frameworks/base/graphics/java/android/graphics/Bitmap.java

或者

http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/1.5_r4/android/graphics/Bitmap.java