加载大图片时采样率怎么计算

对于大图片为了防止OOM,内存溢出,所以采样率就是对图片显示到原来的的1/n大小
计算方法为图片宽度/控件宽度和图片高度/控件高度,取两者的最大值

 public void loadPic(View view) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        //当为true时,返回null
        options.inJustDecodeBounds = true;
        //测试所用的大图片
        final Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.head_test, options);
        ImageView imageView = findViewById(R.id.pic);
        //拿到图片的大小
        int outHeight = options.outHeight;
        int outWidth = options.outWidth;
        Log.e(TAG, outHeight + " " + outWidth + "");

        //拿到控件的大小
        int measuredHeight = imageView.getMeasuredHeight();
        int measuredWidth = imageView.getMeasuredWidth();
        Log.e(TAG, measuredHeight + " " + measuredWidth);

        //默认为1
        options.inSampleSize = 1;

        //图片的宽度/控件的宽度
        //图片的高度/控件的高度
        //取两者的大值

        if (outHeight > measuredHeight || outWidth > measuredWidth) {
            int subHeight = outHeight / measuredHeight;
            int subWidth = outWidth / measuredWidth;
            options.inSampleSize = subHeight > subWidth ? subHeight : subWidth;
        }

        options.inJustDecodeBounds = false;
        Log.e(TAG, options.inSampleSize+" " );
        imageView.setImageBitmap(bitmap);

    }

你可能感兴趣的:(加载大图片时采样率怎么计算)