美文网首页图片android技术杂荟Android开发
ImageView按图片自身比例展示

ImageView按图片自身比例展示

作者: juexingzhe | 来源:发表于2017-09-07 00:11 被阅读209次

    上一篇博客已经是7月25号了,最近也是一直在忙项目的事情,项目上线了想着就遇到的技术问题记录下来。今天我们来看一个ImageView
    展示图片的问题,需求是这样,ImageView宽度是手机屏幕宽度,ImageView高度需要根据图片自适应调整,也就是最终需要看起来图片不要有拉伸或者压缩的感觉。我们今天用两种方法来实现这个需求。

    后面内容主要包含下面两个内容:

    1.自定义ImageView实现图片按比例展示
    
    2.Glide实现图片按比例展示
    

    先看下最后实现的效果:

    这个是在模拟器上跑的效果,下面两个图的效果其实是一样的,一屏容不下,往下滚动是可以看到一样的效果。

    效果图.png

    简单说下三个图分别表达什么意思,第一个图对ImageView设置了高度wrap_content宽度match_parent和scaleType = fitXY,可以看到宽度是有屏幕宽了,但是图片高度不对,明显压缩变形了,所以常规的方法肯定是不行了。这才有我们今天这篇分享的必要性。

    第二个图是通过自定义View实现,第三个图是通过Glide开源库的方法实现。后面我们详细分解。

    1.自定义ImageView实现

    自定义View的实现方式主要原理,先测量需要展示图片的宽高和比例,然后在系统测量ImageView尺寸的时候把View的宽度设置成手机屏幕宽度,高度就根据图片的比例计算得出。Talk is Cheap, Show me Code。我们看下代码:

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            if (mBitmap == null) return;
    
            int drawableWidth = mBitmap.getIntrinsicWidth();
            int drawableHeight = mBitmap.getIntrinsicHeight();
    
            float ratio = (float) drawableWidth / drawableHeight;
    
            Log.d(TAG, "drawableWidth = " + drawableWidth
                    + " drawableHeight = " + drawableHeight
                    + " ratio = " + ratio);
    
            int width;
            int height;
    
            width = UIUtils.getScreenWidth(this.getContext());
            height = (int) Math.floor(width / ratio + 0.5);
    
            Log.d(TAG, "viewWidth = " + width
                    + " viewHeight = " + height
                    + " viewRatio = " + (float) width / height);
    
            setMeasuredDimension(width, height);
    }
    

    其实都是一些简单的数学运算,小学数学即可,就不多做解释了。我们看下打印出来的log,图片的原始宽度是426,宽高比例是1.5;ImageView的宽度是800,等比例放大后,高度是531。

    AutoImageView: drawableWidth = 426 drawableHeight = 283 ratio = 1.5053004
    AutoImageView: viewWidth = 800 viewHeight = 531 viewRatio = 1.5065913
    

    小伙伴们看了上面的代码有木有发现什么问题?在图片还在onMeasure的时候, mBitmap从哪里来?这其实是自定义里面关键的一步。我实现的办法是在ImageView初始化的时候就去加载得到Drawable:

    private GlideDrawable mBitmap;
    
    public AutoImageView(Context context) {
            super(context);
            init();
    }
    
    private void init() {
        SimpleTarget<GlideDrawable> target = new SimpleTarget<GlideDrawable>() {
                @Override
                public void onResourceReady(GlideDrawable bitmap, GlideAnimation glideAnimation) {
                    mBitmap = bitmap;
                    setBackground(mBitmap);
                }
            };
        Glide.with(this.getContext()).load(R.mipmap.success).into(target);
    }
    

    这里我们通过一个Target来替代ImageView放入到into中,在图片下载完成后Glide会回调onResourceReady,这里我们就可以拿到Drawable。

    说起来比较简单,接下来看看第二种实现方法。

    2.Glide方法实现

    Glide的实现方式顾名思义就是调用Glide的API来帮我们实现需求,不需要去自定义View,灵活性更好一点。实现起来就是一个方法,可以直接写到UIUtils之类的工具类中。我们直接来看下代码:

    public static void imageLoad(final ImageView imageView, final int url) {
          Glide.with(imageView.getContext())
               .load(url)
               .placeholder(R.mipmap.timg)
               .error(R.mipmap.timg)
               .listener(new RequestListener<Integer, GlideDrawable>() {
                   @Override
                   public boolean onException(Exception e, Integer model, Target<GlideDrawable> target, boolean isFirstResource) {
                            return false;
                   }
    
                   @Override
                   public boolean onResourceReady(GlideDrawable resource, Integer model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                       if (imageView.getScaleType() != ImageView.ScaleType.FIT_XY){                            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                       }
    
                       int width = resource.getIntrinsicWidth();
                       int height = resource.getIntrinsicHeight();
    
                       Log.d(TAG, "width = " + width + " height = " + height);
                       float ratio = (float) width / height;
    
                       Log.d(TAG, "ratio = " + ratio);
    
                       ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
                       layoutParams.height = (int) Math.floor(getScreenWidth(imageView.getContext()) / ratio + 0.5);                    layoutParams.width = getScreenWidth(imageView.getContext());
                       imageView.setLayoutParams(layoutParams);
    
                       Log.d(TAG, "viewWidth = " + imageView.getLayoutParams().width
                               + " viewHeight = " + imageView.getLayoutParams().height
                            + " viewRatio = " + (float) imageView.getLayoutParams().width / imageView.getLayoutParams().height);
    
                       return false;
                   }
               })
               .into(imageView);
    
    }
    

    关键逻辑就在listener中,实现RequestListener,在onException中一般直接返回false即可,这样在异常的时候Glide会去加载error设置的drawable,在onResourceReady方法中其实逻辑和上面自定义的方式类似,拿到图片GlideDrawable后计算图片的宽高和比例,然后imageView.getLayoutParams获得ImageView的参数设置进去即可。
    看下log的信息,和上面第一种方式得到一样的结果:

    UIUtils: width = 426 height = 283
    UIUtils: ratio = 1.5053004
    UIUtils: viewWidth = 800 viewHeight = 531 viewRatio = 1.5065913
    

    3.总结

    这次我们分享了两种实现ImageView按图片自身比例展示的方法,一种是自定义的方式,比较不灵活;另外一种是调用Glide的API来实现,比较灵活。两种方式都是一样的原理,就是需要拿到需要展示图片的宽高和比例然后去设置ImageView的layoutParams。

    如果小伙伴们还有其它的实现方法一定要告诉我啊,评论留言。

    今天的分享就到这里了,希望对大家有点帮助,谢谢!

    欢迎关注公众号:JueCode

    相关文章

      网友评论

        本文标题:ImageView按图片自身比例展示

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