Android 图片展示,获取宽高,适配系统,防止图片过大不显示

起因是测试在测试过程中发现需要裁剪的图片看不到,但是还能继续裁剪。
所以就检查代码,发现了bitmap的width和Height有3000多。
然后试了下把图片改成300*300的就显示正常,
所以我们需要让图片根据大小不同,机器不同而改变图片的宽高

  //设置分辨率
            //1.获取系统分辨率
            Resources resources = this.getResources();
            DisplayMetrics dm = resources.getDisplayMetrics();

            //2.获取图片分辨率
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;// 这个方式不会在内存创建一张图片,
            Bitmap bitmap = BitmapFactory.decodeFile(filePath, options); //此时返回的bitmap为null,但是option会保留一部分参数

            //3.确定分辨率
            int height = options.outHeight;
            int width = options.outWidth;

            if(options.outHeight>dm.heightPixels*1.5f){//当图片大小比屏幕大1.5倍的时候,直接以系统高度为高度
                height = dm.heightPixels;
            }
            if (options.outWidth>dm.widthPixels*1.5f){
                width = dm.widthPixels;
            }
            options.inJustDecodeBounds = false;

            //4.创建合适的图片
            bitmap = BitmapUtils.getBitmapFromFilePath(filePath,width,height);//resize图片
            imageView.setImageBitmap(bitmap);

小米,和VIVO用手机拍完照片之后容易出这个问题,分辨率好高。
Bitmap工具函数

 public static Bitmap getBitmapFromFilePath(String filePath, int width, int height) {
        BitmapFactory.Options opts = null;
        if (width > 0 && height > 0) {
            opts = new BitmapFactory.Options();
            opts.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(filePath, opts);
            // 计算图片缩放比例
            final int minSideLength = Math.min(width, height);
            opts.inSampleSize = computeSampleSize(opts, minSideLength,
                    width * height);
            opts.inJustDecodeBounds = false;
            opts.inInputShareable = true;
            opts.inPurgeable = true;
        }
        try {
            return BitmapFactory.decodeFile(filePath, opts);
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
        }
        return null;
    }

需要的话,可以考虑下改造Bitmap工具函数,减少代码量

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,826评论 25 709
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,783评论 0 17
  • 一、概述 相信大家都用过 Android 应用中更换头像的功能,在这个功能中,用户可以拍照或者选择相册图片,然后裁...
    东方未曦阅读 9,597评论 19 20
  • 如果晚点相遇, 你刚好温柔,我刚好成熟, 我们会不会走到最后。 [心]
    是草莓啊阅读 147评论 0 0
  • 四年级三班徐雨恒 10月12日码头小学联合威海晚报,在学校德育处杨主任的带领下,走进刘公岛,开展了丰富多彩...
    徐雨恒阅读 368评论 0 1