溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么在Android中使用Picasso加載網絡圖片

發(fā)布時間:2021-03-26 16:57:26 來源:億速云 閱讀:154 作者:Leah 欄目:移動開發(fā)

怎么在Android中使用Picasso加載網絡圖片?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。

通過Picasso來縮放

其實picasso提供了這樣的方法。具體是顯示Transformation 的 transform 方法。

(1) 先獲取網絡或本地圖片的寬高
(2) 獲取需要的目標寬
(3) 按比例得到目標的高度
(4) 按照目標的寬高創(chuàng)建新圖

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來完成。

看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業(yè)資訊頻道,感謝您對億速云的支持。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI