Как уменьшить изображения, используемые в ViewPager Android?

Я следовал этому руководству http://mobile.tutsplus.com/tutorials/android/android-user-interface-design-horizontal-view-paging/

У меня есть адаптер пейджера, который выглядит так (коды ниже), и я получаю сообщение об ошибке, говорящее, что мое изображение слишком велико. (java.lang.OutOfMemoryError: размер растрового изображения превышает бюджет виртуальной машины.)

Я знаю, что многие задавали этот вопрос, и я погуглил и нашел много решений. Тем не менее, я не мог, похоже, запустить его правильно. Я новичок и надеюсь получить некоторые ответы здесь, так как понятия не имею, что еще мне делать.

Декодирование растрового изображения предназначено для изображения, но что, если мои изображения находятся в макетах, как показано ниже. Как уменьшить масштаб изображений?

public class TutorialPagerAdapter extends PagerAdapter {

Activity activity;
int imageArray[];
private Resources resource;  


    private class MyPagerAdapter extends PagerAdapter {
    public int getCount() {
        return 5;
    }
    public Object instantiateItem(View collection, int position) {
        LayoutInflater inflater = (LayoutInflater) collection.getContext()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        int resId = 0;
        switch (position) {
        case 0:
            resId = R.layout.farleft;
        try{
            mImageView = (ImageView) collection.findViewById(R.id.tutorial);
            mImageView.setImageBitmap(decodeSampledBitmapFromResource(activity.getResources(), R.id.tutorial, 100, 100));
            }
            catch (NullPointerException e)
            {
                e.printStackTrace();
            }

            break;
        case 1:
            resId = R.layout.left;
            break;
        case 2:
            resId = R.layout.middle;
            break;
        case 3:
            resId = R.layout.right;
            break;
        case 4:
            resId = R.layout.farright;
            break;
        }
        View view = inflater.inflate(resId, null);

        ((ViewPager) collection).addView(view, 0);
        return view;
    }
    @Override
    public void destroyItem(View arg0, int arg1, Object arg2) {
        ((ViewPager) arg0).removeView((View) arg2);
    }
    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == ((View) arg1);
    }
    @Override
    public Parcelable saveState() {
        return null;
    }


public static Bitmap decodeSampledBitmapFromResource(String res, int reqWidth, int reqHeight) {      

    // First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(res, options);

 // Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(res, options);
  }


public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;

if (height > reqHeight || width > reqWidth) {
    if (width > height) {
        inSampleSize = Math.round((float)height / (float)reqHeight);
    } else {
        inSampleSize = Math.round((float)width / (float)reqWidth);
                  }
                      }
return inSampleSize;}

}

ИЗМЕНИТЬ

Я пробовал mImageView.setImageBitmap(decodeSampledBitmapFromResource...), но получаю исключение Null Pointer Exception в этой строке.


person Honey H    schedule 19.12.2012    source источник


Ответы (1)


попробуйте этот код, может быть, он вам полезен, он связан с двумя изображениями в пейджере просмотра Как увеличить масштаб и провести пальцем по нескольким изображениям в Android?.

person urveshpatel50    schedule 19.12.2012
comment
Я попробовал метод, который использовал этот человек, но он, похоже, не сработал. Я пробовал mImageView.setImageBitmap(decodeSampledBitmapFromResource...), но получаю исключение NullPointerException. И у меня на самом деле есть 2 изображения в каждом макете. А всего у меня 9 раскладок. - person Honey H; 19.12.2012
comment
mImageView.setImageBitmap(decodeSampledBitmapFromResource(activity.getResources(), R.drawable.ic_launcher, 100, 100)); замени это - person urveshpatel50; 19.12.2012