Android 使用Picasso加载网络图片等比例缩放

在做android图片加载的时候,由于手机屏幕受限,很多大图加载过来的时候,我们要求等比例缩放,比如按照固定的宽度,等比例缩放高度,使得图片的尺寸比例得到相应的缩放,但图片没有变形。显然按照android:scaleType不能实现,因为会有很多限制,所以必须要自己写算法。
之前也写过一篇文章Android根据屏幕宽度缩放图片,但这是缩放的本地图片,网络图片该如何办呢?

通过Picasso来缩放
其实picasso提供了这样的方法。具体是显示Transformation 的transform方法。
1、先获取网络或本地图片的宽高
2、获取需要的目标宽
3、按比例得到目标的高度
4、按照目标的宽高创建新图

Transformation transformation = new Transformation() {

        @Override
        public Bitmap transform(Bitmap source) {

        int targetWidth = mImg.getWidth();
        LogCat.i("source.getHeight()="+source.getHeight()+",source.getWidth()="+source.getWidth()+",targetWidth="+targetWidth);

        if(source.getWidth()==0){
            return source;
        }

        //如果图片小于设置的宽度,则返回原图
        if(source.getWidth()<targetWidth){
            return source;
        }else{
            //如果图片大小大于等于设置的宽度,则按照设置的宽度比例来缩放
            double aspectRatio = (double) source.getHeight() / (double) source.getWidth();
            int targetHeight = (int) (targetWidth * aspectRatio);
            if (targetHeight != 0 && targetWidth != 0) {
                Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
                if (result != source) {
                    // Same bitmap is returned if sizes are the same
                    source.recycle();
                }
                return result;
            } else {
                return source;
            }
        }

    }

        @Override
        public String key() {
            return "transformation" + " desiredWidth";
        }
    };

之后在Picasso设置transform

            Picasso.with(mContext)
                    .load(imageUrl)
                    .placeholder(R.mipmap.zhanwei)
                    .error(R.mipmap.zhanwei)
                    .transform(transformation)
                    .into(viewHolder.mImageView);

参考文献:
http://stackoverflow.com/questions/21889735/resize-image-to-full-width-and-variable-height-with-picasso
http://blog.csdn.net/larryl2003/article/details/6919513

你可能感兴趣的:(算法,android,Picasso,Glide,等比缩放)