我非常了解OutOfMemoryError地狱,使用位图可以将大量图像应用放入其中。通常,我总是通过自适应缩放图像,使用缓存等方法来解决此问题。

但是,目前,我在一个应用程序上工作,其中一个用例是能够拍摄图像并通过另一张较小的图像自动为其添加水印(即与之合并)。该规范明确指出,品牌形象必须与原始形象具有相同的大小和质量,因此我无法缩放。

我已经发现这是不可能实现的:即使设置了android:largeHeap =“ true”,尝试创建尺寸与原始图像相同的位图也会在用于测试的Galaxy S3上始终抛出OOME。

有没有可能解决这个问题?

相关代码为:

private Bitmap mergeImages(Bitmap firstImage, Bitmap secondImage) {

    Bitmap.Config config = (firstImage.getConfig() != null) ? firstImage.getConfig() : Bitmap.Config.ARGB_8888;
    Bitmap resultImage = Bitmap.createBitmap(
            Math.max(firstImage.getWidth(), secondImage.getWidth()),
            Math.max(firstImage.getHeight(), secondImage.getHeight()),
            config);

    Canvas mergeCanvas = new Canvas(resultImage);
    Paint paint = new Paint();
    mergeCanvas.drawBitmap(firstImage, 0, 0, paint);
    mergeCanvas.drawBitmap(secondImage, 0, 0, paint);

    return resultImage;
}

最佳答案

我们在我的应用程序中使用两个位图进行了类似的合并效果,而实现此效果的方法是对两个位图都使用RelativeLayout容器,以便它们出现在同一位置,一个覆盖在另一个位置:

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="10dp"
     >

<ImageView
    android:id="@+id/discovery_row_photo"
    android:layout_width="130dp"
    android:layout_height="130dp" />

<ImageView
    android:id="@+id/discovery_row_photo_corner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@id/discovery_row_photo"
    android:layout_alignTop="@id/discovery_row_photo"
    android:contentDescription="@null"
    android:src="@drawable/discovery_corner_badge" />
</RelativeLayout>


第二个ImageView是我认为要使用的“水印”。这样,我们缩放原始图像discovery_row_photo,并将discovery_row_photo_corner放置在其顶部。由于第二个主要是透明的,因此效果很好。不知道这是否适用于您的用例,但这是一个有用的技巧。

关于java - Android:无法缩放时管理位图内存,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23351068/

10-16 21:58