如何在Android Studio中加载多张图片时防止延迟

时间:2015-10-18 23:19:38

标签: java android android-studio imageview lag

我需要从画廊中获取4张照片......

当我触摸我的活动中的4 ImageView之一时,它会调用以下代码:

public void imagePicker(View view)
{
    Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
    photoPickerIntent.setType("image/*");
    startActivityForResult(photoPickerIntent, view.getId());
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    ImageView image1=(ImageView)findViewById(R.id.image1);
    ImageView image2=(ImageView)findViewById(R.id.image2);
    ImageView image3=(ImageView)findViewById(R.id.image3);
    ImageView image4=(ImageView)findViewById(R.id.image4);

    if ((requestCode == R.id.image1 || requestCode == R.id.image2 || requestCode == R.id.image3 || requestCode == R.id.image4) && resultCode == RESULT_OK && data != null)
    {
        Uri pickedImage = data.getData();
        String[] filePath = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
        cursor.moveToFirst();
        String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
        switch(requestCode)
        {
            case R.id.image1:
                image1.setImageBitmap(bitmap);
                break;
            case R.id.image2:
                image2.setImageBitmap(bitmap);
                break;
            case R.id.image3:
                image3.setImageBitmap(bitmap);
                break;
            case R.id.image4:
                image4.setImageBitmap(bitmap);
                break;
        }
        cursor.close();
    }

但是当它加载第二张图片时,Activity开始滞后。 那么,我该如何避免这种情况呢?我认为我可以降低ImageView的分辨率并将原始图像存储在其他地方。如果这样可行,我该怎么办?

1 个答案:

答案 0 :(得分:1)

尝试缩放bitmap以降低其实际分辨率,我已使用以下代码来缩小bitmap的尺寸。

int nh = (int) (bitmap.getHeight() * (512.0 / bitmap.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 512, nh, true);