android - 在android中显示图像和管理内存

标签 android

我编写了一个程序,可以随时在屏幕上显示 8 个用户选择的图像。每个图像都取自其原始形式并按比例缩小到统一尺寸。为此,我使用以下代码:

Bitmap bitmapOrg = BitmapFactory.decodeFile(File Location Here);

        int width = bitmapOrg.getWidth();
        int height = bitmapOrg.getHeight();
        int newWidth = 100;
        int newHeight = 100;

        // calculate the scale - in this case = 0.4f
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        // createa matrix for the manipulation
        Matrix matrix = new Matrix();
        // resize the bit map
        matrix.postScale(scaleWidth, scaleHeight);

        // recreate the new Bitmap
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, width,
                height, matrix, true);
        // make a Drawable from Bitmap to allow to set the BitMap
        // to the ImageView, ImageButton or what ever
        BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);

        //ImageView imageView = new ImageView(this);
        ImageView iv = (ImageView) findViewById(R.id.imageView1);

        // set the Drawable on the ImageView
        iv.setImageDrawable(bmd);

        // center the Image
        iv.setScaleType(ScaleType.CENTER);

尽管我的代码可以正常工作,但它并不完美。似乎我用掉了很多内存,尤其是一次可能调用此代码 8 次。我应该在代码的什么地方“回收”内存,我怎样才能使这段代码运行得更好?

编辑:

所以我在我的项目中实现了代码,它运行完美,然后我尝试将它添加到其他部分,但它只是停止一起工作。我的代码如下所示:知道我做错了什么吗?

    BitmapFactory.Options options = new BitmapFactory.Options(); 
 options.outWidth = 50; 
 options.outHeight = 50; Bitmap bitmap = BitmapFactory.decodeFile(path, options);
 ImageView iv = (ImageView) findViewById(R.id.imageView7); 
 iv.setImageBitmap(bitmap);

最佳答案

您可以使用 BitmapFactory.Options 在解码时缩放图像,而不是读取完整图像然后缩放。

BitmapFactory.Options options = new BitmapFactory.Options();
// You can play with this setting depending on how large your images are
// For example, to scale ~400x400 images to ~100x100, you can use 4.
options.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(path, options);

编辑 - George 是正确的。您应该使用 inSampleSize 创建您需要的一般大小的较小图像,然后使用 ImageView 将其调整为您想要的确切大小。我已经更正了上面的答案以反射(reflect)这一点。

在任何情况下,如果您在解码期间缩放位图,您应该在内存方面做得更好。

关于android - 在android中显示图像和管理内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5412168/

相关文章:

android - AppBarLayout.setExpanded(boolean, true) 支持库 23.1.1 中的奇怪动画

android - 使用 LocationClient 获取位置更新

javascript - Nativescript 无法使 android 通知操作正常工作

android:layout_below 无法正常工作

java - 将顶点放入顶点缓冲区时出现 BufferOverFlowException

android - 使用两个项目的ClassNotFoundException

android - 手动执行 Intent 并获得结果

java - Android相机存储图像(原始): Strange pictures after update

Android关闭滚动动画

android - MediaPlayer 在带有 R.raw 音频的 setDataSource 上崩溃