Android 使用Picasso載入網狀圖片等比例縮放

來源:互聯網
上載者:User

標籤:寬高   code   sam   ref   tran   for   desire   transform   ima   

在做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

Android 使用Picasso載入網狀圖片等比例縮放

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.