美文网首页
ImageView加载大图片解决OOM错误的问题,使用optio

ImageView加载大图片解决OOM错误的问题,使用optio

作者: 深埋的心 | 来源:发表于2020-07-12 18:31 被阅读0次

     编码过程中如果Imageview加载大图片的时候,有可能会出现oom错误,那么就需要修改BitmapFactory.Options options = new BitmapFactory.Options(),的options参数来处理图片,让图片适当的缩放来正确的显示.

    代码如下

    public void loadBigImage(View view) {

    ImageView imageView =this.findViewById(R.id.image_container);

        BitmapFactory.Options options =new BitmapFactory.Options();

        //If set to true, the decoder will return null (no bitmap)

        //设置为true以后呢,不是真的载入到内存中,只是获取到图片的相关信息

        options.inJustDecodeBounds =true;

        BitmapFactory.decodeResource(getResources(),R.mipmap.test_pic,options);

        int width = options.outWidth;//得到资源文件中图片的宽度

        int height = options.outHeight;//得到资源文件中图片的高度

        int measuredWidth = imageView.getMeasuredWidth();//获得控件的宽度

        int measuredHeight = imageView.getMeasuredHeight();//多的控件的高度

        Log.d(TAG,"width -- > " + width +" measure width -- > " + measuredWidth);

        Log.d(TAG,"measuredWidth -- > " + measuredWidth +" measuredHeight  -- > " + measuredHeight );

        int sampleSize;//缩放的倍数  如果是4,图片会缩放为原来的四分之一

        if(width < measuredWidth || height < measuredHeight) {

    //如果图片的高度或者宽度小于控件的高度或宽度,则不用sampleSize设置为1,正常显示

    sampleSize =1;

        }else {

            int scaleX = width / measuredWidth;

            int scaleY = height / measuredHeight;

            sampleSize = scaleX > scaleY ? scaleX : scaleY;//那个商大用那个,防止图片变形或挤压

        }

    Log.d(TAG,"sampleSize -- > " + sampleSize);

        options.inSampleSize = sampleSize;

        //If set to true, the decoder will return null (no bitmap)

        //要变成false了,因为真的要载入到内存中了

        options.inJustDecodeBounds =false;

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.mipmap.test_pic,options);

        imageView.setImageBitmap(bitmap);

    }

    相关文章

      网友评论

          本文标题:ImageView加载大图片解决OOM错误的问题,使用optio

          本文链接:https://www.haomeiwen.com/subject/jnlncktx.html