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());
        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-picassoide

相關文章
相關標籤/搜索