decodeStream不会使用Bitmap图像填充recyclerView

时间:2016-10-18 13:37:29

标签: android android-recyclerview android-bitmap

我想用小(60x60)专辑艺术位图填充我的recyclerview,但我似乎无法得到它。我已经尝试过我所知道的一切,请帮忙。

我用来缩小图片的代码:

public static int calculateSize(BitmapFactory.Options opt, int reqHeight, int reqWidth){
        int height = opt.outHeight;
        int width = opt.outWidth;
        int inSampleSize = 1;

        if(height > reqHeight || width > reqWidth){

            final int halfWidth = width/2;
            final int halfHeight = height /2;

            while((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth){
                inSampleSize *= 2;

            }
        }

        return inSampleSize;
    }

    public Bitmap decodeSampleBitmapFromArray(InputStream stream, Rect rect, int reqHeight, int reqWidth){
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap bit = BitmapFactory.decodeStream(stream, rect, options);

        //Calculate sample size
        options.inSampleSize = calculateSize(options, reqHeight, reqWidth);

        //Decode bitmap with insamplesize set false
        options.inJustDecodeBounds = false;
        return bit;
    }

然后我在onCreate方法中调用了decodeSampleBitmapFromArray函数,以便填充我的recyclerview适配器:

@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
...

    adapter = new CustomRecycler(paths);
    recyclerView = (RecyclerView)v.findViewById(R.id.ryc);

    lManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(lManager);
    recyclerView.setHasFixedSize(true);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(adapter);
        metaRetriever.setDataSource(path);
        byte[] b = metaRetriever.getEmbeddedPicture();

        if (b != null) {
            InputStream in = new ByteArrayInputStream(b);
            paths.add(decodeSampleBitmapFromArray(in,new Rect(-1,-1,1,1), 60, 60));

        }else{
            Bitmap altIcon = BitmapFactory.decodeResource(getResources(), R.drawable.beat);
            paths.add(altIcon);
        }

}

我的RecyclerAdapter然后收到位图并使用ImageView

显示它
holder.artImage.setImageBitmap(mImage.get(position));

完成所有这些操作后,图像仍未填充Recyclerview。我做错了什么?提前致谢

1 个答案:

答案 0 :(得分:2)

当你设置options.inJustDecodeBounds = true时,这正是发生的事情 - 它只是对边界进行解码。始终为位图返回Null。我们的想法是,一旦您知道边界,就可以将options.inSampleSize设置为适当的值并再次解码图像数据。

仔细查看此开发者页面中的方法decodeSampleBitmapFromResourcehttps://developer.android.com/training/displaying-bitmaps/load-bitmap.html#load-bitmap

BitmapFactory.decodeResource被称为两次,首先使用options.inJustDecodeBounds = true获取维度,然后设置options.inSampleSize以生成按您希望的方式缩放的位图。< / p>

您的代码正在为options.inSampleSize获取值,但您永远不会再使用此值调用BitmapFactory.decodeStream()来检索缩放的位图。