2015-11-14 93 views
7

我想在使用Glide在位圖裁剪和重新調整大小後加載位圖到ImageView。使用glide將位圖加載到ImageView

我不想使用ImageView.setImageBitmap(bitmap);,因爲我加載了大量的圖像,它可能佔用了一些內存,儘管圖像尺寸很小,我只需要使用Glide,因爲我知道它優化了圖像緩存。

我讀this後,但我不明白他的解決方案,當我嘗試實施它。所以也許有人有一個更清潔,更容易理解的解決方案。

這是我的代碼,它拾取一個圖像,並創建一個位圖。

我需要使用滑行代替ImageView.setImageBitmap(bitmap);

new AsyncTask<String, Void, Void>() { 
    Bitmap theBitmap = null; 
    Bitmap bm = null; 

    @Override 
    protected Void doInBackground(String... params) { 
     String TAG = "Error Message: "; 
     try { 
      //Load the image into bitmap 
      theBitmap = Glide. 
        with(mContext). 
        load("http://example.com/imageurl"). 
        asBitmap(). 
        into(-1, -1). 
        get(); 

      //resizes the image to a smaller dimension out of the main image. 
      bm = Bitmap.createBitmap(theBitmap, 0, 0, 210, 80); 
     } catch (final ExecutionException e) { 
      Log.e(TAG, e.getMessage()); 
     } catch (final InterruptedException e) { 
      Log.e(TAG, e.getMessage()); 
     } catch (final NullPointerException e) { 
      // 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(Void dummy) { 
     if (null != theBitmap) { 
      //Set image to imageview. 
      **// I would like to Use Glide to set the image view here Instead of .setImageBitmap function** 
      holder.mImageView.setImageBitmap(bm); 

      holder.mImageView.setAdjustViewBounds(true); 
      holder.mImageView.setScaleType(ImageView.ScaleType.CENTER_CROP); 
     } 
    } 
}.execute(); 
+0

你能告訴我你的問題是什麼?位圖爲空或您的ImageView顯示白色方塊? –

+0

不,位圖不爲空,我需要使用Glide將位圖圖像設置爲ImageView,而不是直接設置它。 –

+0

原因是因爲我正在加載大量需要內存緩存的圖像。你明白我的意思嗎? –

回答

18

你不需要AsyncTask加載圖像與Glide。滑動加載圖像異步。 嘗試使用此代碼:

Glide.with(mContext) 
       .load("http://example.com/imageurl") 
       .asBitmap() 
       .into(new SimpleTarget<Bitmap>() { 
        @Override 
        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { 
         // you can do something with loaded bitmap here 

         // ..... 

         holder.mImageView.setImageBitmap(resource); 
        } 
       }); 
+0

不,我想裁剪圖像到TOP,而不是centerCrop,這就是爲什麼我選擇從中創建一個位圖,然後給它(0,0,210,80),以便裁剪到這個尺寸並開始從頂部而不是中心。 –

+0

我編輯了我的答案,請檢查此。 p.s.您是否使用常量值(例如210,80)在頂部啓動位圖?我認爲這是不實際的,你應該使用自定義的'可繪製的'與頂部對齊。 –

+0

謝謝,但這也不起作用,當你在onResourceReady裏面創建你的位圖時,它仍然和它在外面的onResourceReady時一樣。沒有變化! –