亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Android 使用Picasso加載網(wǎng)絡圖片等比例縮放的實現(xiàn)方法

 更新時間:2018年08月05日 09:39:16   作者:記錄自己的點點滴滴  
在做android圖片加載的時候,由于手機屏幕受限,很多大圖加載過來的時候,我們要求等比例縮放,接下來小編給大家?guī)砹薃ndroid 使用Picasso加載網(wǎng)絡圖片等比例縮放的實現(xiàn)方法,感興趣的朋友一起看看吧

在做android圖片加載的時候,由于手機屏幕受限,很多大圖加載過來的時候,我們要求等比例縮放,比如按照固定的寬度,等比例縮放高度,使得圖片的尺寸比例得到相應的縮放,但圖片沒有變形。顯然按照android:scaleType不能實現(xiàn),因為會有很多限制,所以必須要自己寫算法。

通過Picasso來縮放

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

(1) 先獲取網(wǎng)絡或本地圖片的寬高
(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來完成。

參考文章: https://stackoverflow.com/questions/21889735/resize-image-to-full-width-and-variable-height-with-picasso

總結(jié)

以上所述是小編給大家介紹的Android 使用Picasso加載網(wǎng)絡圖片等比例縮放的實現(xiàn)方法,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!

相關(guān)文章

最新評論