温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在Android中使用Picasso加载网络图片

发布时间:2021-03-26 16:57:26 来源:亿速云 阅读:149 作者:Leah 栏目:移动开发

怎么在Android中使用Picasso加载网络图片?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

通过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来完成。

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI