欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

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

通過Picasso來縮放

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

(1) 先獲取網(wǎng)絡(luò)或本地圖片的寬高
(2) 獲取需要的目標(biāo)寬
(3) 按比例得到目標(biāo)的高度
(4) 按照目標(biāo)的寬高創(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;
      }
      //如果圖片小于設(shè)置的寬度,則返回原圖
      if(source.getWidth()<targetWidth){
        return source;
      }else{
        //如果圖片大小大于等于設(shè)置的寬度,則按照設(shè)置的寬度比例來縮放
        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設(shè)置transform

Picasso.with(mContext)
      .load(imageUrl)
      .placeholder(R.mipmap.zhanwei)
      .error(R.mipmap.zhanwei)
      .transform(transformation)
      .into(viewHolder.mImageView);

Transformation 這是Picasso的一個(gè)非常強(qiáng)大的功能了,它允許你在load圖片 -> into ImageView 中間這個(gè)過成對圖片做一系列的變換。比如你要做圖片高斯模糊、添加圓角、做度灰處理、圓形圖片等等都可以通過Transformation來完成。

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

總結(jié)

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

相關(guān)文章

最新評論