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


    在做android图片加载的时候,由于手机屏幕受限,很多大图加载过来的时候,我们要求等比例缩放,比如按照固定的宽度,等比例缩放高度,使得图片的尺寸比例得到相应的缩放,但图片没有变形。显然按照android:scaleType不能实现,因为会有很多限制,所以必须要自己写算法。 

    通过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());
            LogCat.i("source.getWidth()="+source.getWidth());
           LogCat.i("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);

    Transformation 这是Picasso的一个非常强大的功能了,它允许你在load图片 -> into ImageView 中间这个过成对图片做一系列的变换。比如你要做图片高斯模糊、添加圆角、做度灰处理、圆形图片等等都可以通过Transformation来完成。
    参考文章: https://stackoverflow.com/questions/21889735/resize-image-to-full-width-and-variable-height-with-picasso

  • 相关阅读:
    Docker
    Docker
    Docker
    Docker
    Docker
    Docker
    pandas——向已经存在的excel数据写入data
    python——利用UI选择路径
    python——装饰器的使用
    python——生成器(协程)gevent多任务
  • 原文地址:https://www.cnblogs.com/jiangzhishan/p/9415066.html
Copyright © 2020-2023  润新知