Glide详解

<div id="article_content" class="article_content tracking-ad" data-mod="popu_307" data-dsm="post">
        <div class="markdown_views"><blockquote>
  <p>该文章基于Glide v3.7.0版本 <br>
  Glide v4版本详解请移步: <a href="http://blog.csdn.net/shangmingchao/article/details/78219558" target="_blank">http://blog.csdn.net/shangmingchao/article/details/78219558</a></p>
</blockquote>



<h3 id="一-下载"><a name="t0" target="_blank"></a><strong>一. 下载</strong></h3>

<p>在build.gradle中添加依赖:</p>



<pre class="prettyprint" name="code"><code class="language-gradle hljs bash has-numbering">    compile <span class="hljs-string">'com.github.bumptech.glide:glide:3.7.0'</span></code><ul class="pre-numbering" style=""><li>1</li></ul></pre>

<p>需要support-v4库的支持,如果你的项目没有support-v4库(项目默认已经添加了),还需要添加support-v4依赖:</p>



<pre class="prettyprint" name="code"><code class="language-gradle hljs bash has-numbering">    compile <span class="hljs-string">'com.android.support:support-v4:23.3.0'</span></code><ul class="pre-numbering" style=""><li>1</li></ul></pre>

<p>然后配置混淆规则:</p>



<pre class="prettyprint" name="code"><code class="hljs java has-numbering">    -keep <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> * <span class="hljs-keyword">implements</span> <span class="hljs-title">com</span>.<span class="hljs-title">bumptech</span>.<span class="hljs-title">glide</span>.<span class="hljs-title">module</span>.<span class="hljs-title">GlideModule</span>
    -<span class="hljs-title">keep</span> <span class="hljs-title">public</span> <span class="hljs-title">enum</span> <span class="hljs-title">com</span>.<span class="hljs-title">bumptech</span>.<span class="hljs-title">glide</span>.<span class="hljs-title">load</span>.<span class="hljs-title">resource</span>.<span class="hljs-title">bitmap</span>.<span class="hljs-title">ImageHeaderParser</span>$** {</span>
      **[] $VALUES;
      <span class="hljs-keyword">public</span> *;
    }</code><ul class="pre-numbering" style=""><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul></pre>

<p>其中第一个混淆规则表明不混淆所有的<code>GlideModule</code>。 <br>
如果需要的话,还需添加相应的权限:</p>



<pre class="prettyprint" name="code"><code class="language-xml hljs  has-numbering">    <span class="hljs-tag"><<span class="hljs-title">uses-permission</span> <span class="hljs-attribute">android:name</span>=<span class="hljs-value">"android.permission.INTERNET"</span> /></span>
    <span class="hljs-tag"><<span class="hljs-title">uses-permission</span> <span class="hljs-attribute">android:name</span>=<span class="hljs-value">"android.permission.WRITE_EXTERNAL_STORAGE"</span> /></span></code><ul class="pre-numbering" style=""><li>1</li><li>2</li></ul></pre>

<p>Glide Repo:<a href="https://github.com/bumptech/glide" target="_blank">bumptech/glide</a></p>



<h3 id="二-集成网络框架okhttp可选"><a name="t1" target="_blank"></a><strong>二. 集成网络框架OkHttp(可选)</strong></h3>

<p>Glide的网络请求部分可以使用当前最流行的网络请求框架Volley或OkHttp,也可以通过Glide的ModelLoader接口自己写网络请求。 <br>
Glide默认使用<code>HttpUrlConnection</code>进行网络请求,为了让APP保持一致的网络请求形式,可以让Glide使用我们指定的网络请求形式请求网络资源,这里我们选<a href="https://github.com/square/okhttp" target="_blank">OkHttp</a> (具有支持HTTP/2、利用连接池技术减少请求延迟、缓存响应结果等等优点),需要添加一个集成库:</p>



<pre class="prettyprint" name="code"><code class="language-gradle hljs cs has-numbering">    <span class="hljs-comment">//OkHttp 2.x</span>
    <span class="hljs-comment">//compile 'com.github.bumptech.glide:okhttp-integration:1.4.0@aar'</span>
    <span class="hljs-comment">//compile 'com.squareup.okhttp:okhttp:2.7.5'</span>

    <span class="hljs-comment">//OkHttp 3.x</span>
    compile <span class="hljs-string">'com.github.bumptech.glide:okhttp3-integration:1.4.0@aar'</span>
    compile <span class="hljs-string">'com.squareup.okhttp3:okhttp:3.2.0'</span></code><ul class="pre-numbering" style=""><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li></ul></pre>

<blockquote>
  <p>注意: <br>
  1. OkHttp 2.x和OkHttp 3.x需使用不同的集成库。 <br>
  2. Gradle会自动将OkHttpGlideModule合并到应用的manifest文件中。 <br>
  3. 如果你没有对所有的<code>GlideModule</code>配置混淆规则(即没有使用<code>-keep public class * implements com.bumptech.glide.module.GlideModule</code>),则需要把OkHttp的<code>GlideModule</code>进行防混淆配置:</p>
  
  <pre class="prettyprint" name="code"><code class="hljs avrasm has-numbering">-keep class <span class="hljs-keyword">com</span><span class="hljs-preprocessor">.bumptech</span><span class="hljs-preprocessor">.glide</span><span class="hljs-preprocessor">.integration</span><span class="hljs-preprocessor">.okhttp</span><span class="hljs-preprocessor">.OkHttpGlideModule</span></code><ul class="pre-numbering" style=""><li>1</li></ul></pre>
</blockquote>



<h3 id="三-使用"><a name="t2" target="_blank"></a><strong>三. 使用</strong></h3>



<h4 id="简单使用"><a name="t3" target="_blank"></a><strong>简单使用</strong>:</h4>



<pre class="prettyprint" name="code"><code class="language-java hljs  has-numbering">Glide
    .with(<span class="hljs-keyword">this</span>)
    .load(<span class="hljs-string">"http://inthecheesefactory.com/uploads/source/nestedfragment/fragments.png"</span>)
    .into(imageView);</code><ul class="pre-numbering" style=""><li>1</li><li>2</li><li>3</li><li>4</li></ul></pre>



<h4 id="glidewith使用"><a name="t4" target="_blank"></a><strong>Glide.with()使用</strong></h4>

<ol>
<li>with(Context context). 使用Application上下文,Glide请求将不受Activity/Fragment生命周期控制。</li>
<li>with(Activity activity).使用Activity作为上下文,Glide的请求会受到Activity生命周期控制。</li>
<li>with(FragmentActivity activity).Glide的请求会受到FragmentActivity生命周期控制。</li>
<li>with(android.app.Fragment fragment).Glide的请求会受到Fragment 生命周期控制。</li>
<li>with(android.support.v4.app.Fragment fragment).Glide的请求会受到Fragment生命周期控制。</li>
</ol>

<p>返回关联了相应上下文的<code>RequestManager</code>实例。</p>



<h4 id="requestmanagerload使用"><a name="t5" target="_blank"></a><strong>requestManager.load()使用</strong></h4>

<p>Glide基本可以load任何可以拿到的媒体资源,如: <br>
load <strong>SD卡资源</strong>:load("file://"+ Environment.getExternalStorageDirectory().getPath()+"/test.jpg") <br>
load <strong>assets资源</strong>:load("file:///android_asset/f003.gif") <br>
load <strong>raw资源</strong>:load("android.resource://com.frank.glide/raw/raw_1")或load("android.resource://com.frank.glide/raw/"+R.raw.raw_1) <br>
load <strong>drawable资源</strong>:load("android.resource://com.frank.glide/drawable/news")或load("android.resource://com.frank.glide/drawable/"+R.drawable.news) <br>
load <strong>ContentProvider资源</strong>:load("content://media/external/images/media/139469") <br>
load <strong>http资源</strong>:load("<span><a href="https://img-my.csdn.net/uploads/201508/05/1438760757_3588.jpg" target="_blank">https://img-my.csdn.net/uploads/201508/05/1438760757_3588.jpg</a></span>") <br>
load <strong>https资源</strong>:load("<span><a href="https://img.alicdn.com/tps/TB1uyhoMpXXXXcLXVXXXXXXXXXX-476-538.jpg_240x5000q50.jpg_.webp" target="_blank">https://img.alicdn.com/tps/TB1uyhoMpXXXXcLXVXXXXXXXXXX-476-538.jpg_240x5000q50.jpg_.webp</a><span>") <br>
当然,load不限于String类型,还可以: <br>
<code>load(Uri uri)</code>,<code>load(File file)</code>,<code>load(Integer resourceId)</code>,<code>load(URL url)</code>,<code>load(byte[] model)</code>,<code>load(T model)</code>,<code>loadFromMediaStore(Uri uri)</code>。 <br>
load的资源也可以是本地视频,如果想要load网络视频或更高级的操作可以使用<code>VideoView</code>等其它控件完成。 <br>
而且可以使用自己的<code>ModelLoader</code>进行资源加载: <br>
<code>using(ModelLoader<A, T> modelLoader, Class<T> dataClass)</code>,<code>using(final StreamModelLoader<T> modelLoader)</code>,<code>using(StreamByteArrayLoader modelLoader)</code>,<code>using(final FileDescriptorModelLoader<T> modelLoader)</code>。 <br>
返回GenericRequestBuilder实例。</span></span></p>



<h4 id="genericrequestbuilder使用"><a name="t6" target="_blank"></a><strong>GenericRequestBuilder使用</strong></h4>

<p><code>GenericRequestBuilder<ModelType,DataType,ResourceType,TranscodeType></code>是最顶层的Request Builder,用于处理选项设置和开始一般resource类型资源的加载。其中<code>ModelType</code>是指代表资源的类型,如"<span><a href="https://img-my.csdn.net/uploads/201508/05/1438760757_3588.jpg" target="_blank">https://img-my.csdn.net/uploads/201508/05/1438760757_3588.jpg</a></span>"这个String就代表了一张图片资源,所以这个ModelType就是String。<code>DataType</code>是指ModelLoader提供的,可以被ResourceDecoder解码的数据类型。<code>ResourceType</code>是指将要加载的resource类型。<code>TranscodeType</code>是指已解码的资源将要被转成的资源类型。</p>

<ol>
<li>thumbnail(float sizeMultiplier). 请求给定系数的缩略图。如果缩略图比全尺寸图先加载完,就显示缩略图,否则就不显示。系数sizeMultiplier必须在(0,1)之间,可以递归调用该方法。</li>
<li>sizeMultiplier(float sizeMultiplier). 在加载资源之前给Target大小设置系数。</li>
<li>diskCacheStrategy(DiskCacheStrategy strategy).设置缓存策略。DiskCacheStrategy.SOURCE:缓存原始数据,DiskCacheStrategy.RESULT:缓存变换(如缩放、裁剪等)后的资源数据,DiskCacheStrategy.NONE:什么都不缓存,DiskCacheStrategy.ALL:缓存SOURC和RESULT。默认采用DiskCacheStrategy.RESULT策略,对于download only操作要使用DiskCacheStrategy.SOURCE。</li>
<li>priority(Priority priority). 指定加载的优先级,优先级越高越优先加载,但不保证所有图片都按序加载。枚举Priority.IMMEDIATE,Priority.HIGH,Priority.NORMAL,Priority.LOW。默认为Priority.NORMAL。</li>
<li>dontAnimate(). 移除所有的动画。</li>
<li>animate(int animationId). 在异步加载资源完成时会执行该动画。</li>
<li>animate(ViewPropertyAnimation.Animator animator). 在异步加载资源完成时会执行该动画。</li>
<li>placeholder(int resourceId). 设置资源加载过程中的占位Drawable。</li>
<li>placeholder(Drawable drawable). 设置资源加载过程中的占位Drawable。</li>
<li>fallback(int resourceId). 设置model为空时要显示的Drawable。如果没设置fallback,model为空时将显示error的Drawable,如果error的Drawable也没设置,就显示placeholder的Drawable。</li>
<li>fallback(Drawable drawable).设置model为空时显示的Drawable。</li>
<li>error(int resourceId).设置load失败时显示的Drawable。</li>
<li>error(Drawable drawable).设置load失败时显示的Drawable。</li>
<li>listener(RequestListener<? super ModelType, TranscodeType> requestListener). 监听资源加载的请求状态,可以使用两个回调:<code>onResourceReady(R resource, T model, Target<R> target, boolean isFromMemoryCache, boolean isFirstResource)</code>和<code>onException(Exception e, T model, Target&lt;R&gt; target, boolean isFirstResource)</code>,但不要每次请求都使用新的监听器,要避免不必要的内存申请,可以使用单例进行统一的异常监听和处理。</li>
<li>skipMemoryCache(boolean skip). 设置是否跳过内存缓存,但不保证一定不被缓存(比如请求已经在加载资源且没设置跳过内存缓存,这个资源就会被缓存在内存中)。</li>
<li>override(int width, int height). 重新设置Target的宽高值(单位为pixel)。</li>
<li>into(Y target).设置资源将被加载到的Target。</li>
<li>into(ImageView view). 设置资源将被加载到的ImageView。取消该ImageView之前所有的加载并释放资源。</li>
<li>into(int width, int height). 后台线程加载时要加载资源的宽高值(单位为pixel)。</li>
<li>preload(int width, int height). 预加载resource到缓存中(单位为pixel)。</li>
<li>asBitmap(). 无论资源是不是gif动画,都作为Bitmap对待。如果是gif动画会停在第一帧。</li>
<li>asGif().把资源作为GifDrawable对待。如果资源不是gif动画将会失败,会回调<code>.error()</code>。</li>
</ol>



<h4 id="技巧"><a name="t7" target="_blank"></a><strong>技巧</strong>:</h4>

<ol>
<li><p>禁止内存缓存:</p>

<pre class="prettyprint" name="code"><code class="language-java hljs  has-numbering">    .skipMemoryCache(<span class="hljs-keyword">true</span>)</code><ul class="pre-numbering" style=""><li>1</li></ul></pre></li>
<li><p>清除内存缓存:</p>

<pre class="prettyprint" name="code"><code class="language-java hljs  has-numbering">    <span class="hljs-comment">// 必须在UI线程中调用</span>
    Glide.get(context).clearMemory();</code><ul class="pre-numbering" style=""><li>1</li><li>2</li></ul></pre></li>
<li><p>禁止磁盘缓存:</p>

<pre class="prettyprint" name="code"><code class="language-java hljs  has-numbering">   .diskCacheStrategy(DiskCacheStrategy.NONE)</code><ul class="pre-numbering" style=""><li>1</li></ul></pre></li>
<li><p>清除磁盘缓存:</p>

<pre class="prettyprint" name="code"><code class="language-java hljs  has-numbering">   <span class="hljs-comment">// 必须在后台线程中调用,建议同时clearMemory()</span>
   Glide.get(applicationContext).clearDiskCache();</code><ul class="pre-numbering" style=""><li>1</li><li>2</li></ul></pre></li>
<li><p>获取缓存大小:</p>

<pre class="prettyprint" name="code"><code class="language-java hljs  has-numbering">   <span class="hljs-keyword">new</span> GetDiskCacheSizeTask(textView).execute(<span class="hljs-keyword">new</span> File(getCacheDir(), DiskCache.Factory.DEFAULT_DISK_CACHE_DIR));</code><ul class="pre-numbering" style=""><li>1</li></ul></pre>

<pre class="prettyprint" name="code"><code class="language-java hljs  has-numbering">class GetDiskCacheSizeTask extends AsyncTask<File, Long, Long> {
<span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> TextView resultView;

<span class="hljs-keyword">public</span> <span class="hljs-title">GetDiskCacheSizeTask</span>(TextView resultView) {
    <span class="hljs-keyword">this</span>.resultView = resultView;
}

<span class="hljs-annotation">@Override</span>
<span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onPreExecute</span>() {
    resultView.setText(<span class="hljs-string">"Calculating..."</span>);
}

<span class="hljs-annotation">@Override</span>
<span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onProgressUpdate</span>(Long... values) { <span class="hljs-comment">/* onPostExecute(values[values.length - 1]); */</span> }

<span class="hljs-annotation">@Override</span>
<span class="hljs-keyword">protected</span> Long <span class="hljs-title">doInBackground</span>(File... dirs) {
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">long</span> totalSize = <span class="hljs-number">0</span>;
        <span class="hljs-keyword">for</span> (File dir : dirs) {
            publishProgress(totalSize);
            totalSize += calculateSize(dir);
        }
        <span class="hljs-keyword">return</span> totalSize;
    } <span class="hljs-keyword">catch</span> (RuntimeException ex) {
        <span class="hljs-keyword">final</span> String message = String.format(<span class="hljs-string">"Cannot get size of %s: %s"</span>, Arrays.toString(dirs), ex);
        <span class="hljs-keyword">new</span> Handler(Looper.getMainLooper()).post(<span class="hljs-keyword">new</span> Runnable() {
            <span class="hljs-annotation">@Override</span>
            <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span>() {
                resultView.setText(<span class="hljs-string">"error"</span>);
                Toast.makeText(resultView.getContext(), message, Toast.LENGTH_LONG).show();
            }
        });
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>L;
}

<span class="hljs-annotation">@Override</span>
<span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onPostExecute</span>(Long size) {
    String sizeText = android.text.format.Formatter.formatFileSize(resultView.getContext(), size);
    resultView.setText(sizeText);
}

<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">long</span> <span class="hljs-title">calculateSize</span>(File dir) {
    <span class="hljs-keyword">if</span> (dir == <span class="hljs-keyword">null</span>) <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
    <span class="hljs-keyword">if</span> (!dir.isDirectory()) <span class="hljs-keyword">return</span> dir.length();
    <span class="hljs-keyword">long</span> result = <span class="hljs-number">0</span>;
    File[] children = dir.listFiles();
    <span class="hljs-keyword">if</span> (children != <span class="hljs-keyword">null</span>)
        <span class="hljs-keyword">for</span> (File child : children)
            result += calculateSize(child);
    <span class="hljs-keyword">return</span> result;
}
}</code><ul class="pre-numbering" style=""><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li><li>24</li><li>25</li><li>26</li><li>27</li><li>28</li><li>29</li><li>30</li><li>31</li><li>32</li><li>33</li><li>34</li><li>35</li><li>36</li><li>37</li><li>38</li><li>39</li><li>40</li><li>41</li><li>42</li><li>43</li><li>44</li><li>45</li><li>46</li><li>47</li><li>48</li><li>49</li><li>50</li><li>51</li><li>52</li><li>53</li><li>54</li></ul></pre></li>
<li><p>指定资源的优先加载顺序:</p>

<pre class="prettyprint" name="code"><code class="language-java hljs  has-numbering">    <span class="hljs-comment">//优先加载</span>
    Glide
        .with(context)
        .load(heroImageUrl)
        .priority(Priority.HIGH)
        .into(imageViewHero);
    <span class="hljs-comment">//后加载</span>
    Glide
        .with(context)
        .load(itemImageUrl)
        .priority(Priority.LOW)
        .into(imageViewItem);</code><ul class="pre-numbering" style=""><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li></ul></pre></li>
<li><p>先显示缩略图,再显示原图:</p>

<pre class="prettyprint" name="code"><code class="language-java hljs  has-numbering">    <span class="hljs-comment">//用原图的1/10作为缩略图</span>
    Glide
        .with(<span class="hljs-keyword">this</span>)
        .load(<span class="hljs-string">"http://inthecheesefactory.com/uploads/source/nestedfragment/fragments.png"</span>)
        .thumbnail(<span class="hljs-number">0.1</span>f)
        .into(iv_0);
    <span class="hljs-comment">//用其它图片作为缩略图</span>
    DrawableRequestBuilder<Integer> thumbnailRequest = Glide
        .with(<span class="hljs-keyword">this</span>)
        .load(R.drawable.news);
    Glide.with(<span class="hljs-keyword">this</span>)
        .load(<span class="hljs-string">"http://inthecheesefactory.com/uploads/source/nestedfragment/fragments.png"</span>)
        .thumbnail(thumbnailRequest)
        .into(iv_0);</code><ul class="pre-numbering" style=""><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li></ul></pre></li>
<li><p>对图片进行裁剪、模糊、滤镜等处理: <br>
推荐使用独立的图片处理库:<a href="https://github.com/wasabeef/glide-transformations" target="_blank">wasabeef/glide-transformations</a>,使用也很简单:</p>

<pre class="prettyprint" name="code"><code class="language-gradle hljs bash has-numbering">    compile <span class="hljs-string">'jp.wasabeef:glide-transformations:2.0.0'</span></code><ul class="pre-numbering" style=""><li>1</li></ul></pre>

<p>之后我们就可以使用GenericRequestBuilder或其子类的<code>transform()</code>或<code>bitmapTransform()</code>方法设置图片转换了:</p>

<pre class="prettyprint" name="code"><code class="language-java hljs  has-numbering">    <span class="hljs-comment">//圆形裁剪</span>
    Glide.with(<span class="hljs-keyword">this</span>)
        .load(<span class="hljs-string">"http://inthecheesefactory.com/uploads/source/nestedfragment/fragments.png"</span>)
        .bitmapTransform(<span class="hljs-keyword">new</span> CropCircleTransformation(<span class="hljs-keyword">this</span>))
        .into(iv_0);
    <span class="hljs-comment">//圆角处理</span>
    Glide.with(<span class="hljs-keyword">this</span>)
        .load(<span class="hljs-string">"http://inthecheesefactory.com/uploads/source/nestedfragment/fragments.png"</span>)
        .bitmapTransform(<span class="hljs-keyword">new</span> RoundedCornersTransformation(<span class="hljs-keyword">this</span>,<span class="hljs-number">30</span>,<span class="hljs-number">0</span>, RoundedCornersTransformation.CornerType.ALL))
        .into(iv_0);
    <span class="hljs-comment">//灰度处理</span>
    Glide.with(<span class="hljs-keyword">this</span>)
        .load(<span class="hljs-string">"http://inthecheesefactory.com/uploads/source/nestedfragment/fragments.png"</span>)
        .bitmapTransform(<span class="hljs-keyword">new</span> GrayscaleTransformation(<span class="hljs-keyword">this</span>))
        .into(iv_0);
    <span class="hljs-comment">//其它变换...</span></code><ul class="pre-numbering" style=""><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li></ul></pre>

<p>可根据情况使用GenericRequestBuilder子类DrawableRequestBuilder的<code>bitmapTransform(Transformation<Bitmap>... bitmapTransformations)</code>,<code>transform(BitmapTransformation... transformations)</code>,<code>transform(Transformation<GifBitmapWrapper>... transformation)</code>,或其子类BitmapRequestBuilder的<code>transform(BitmapTransformation... transformations)</code>,<code>transform(Transformation<Bitmap>... transformations)</code>方法。 <br>
当然如果想自己写Transformation: <br>
最简单的方式就是继承<code>BitmapTransformation</code>:</p>

<pre class="prettyprint" name="code"><code class="language-java hljs  has-numbering"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyTransformation</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">BitmapTransformation</span> {</span>

    <span class="hljs-keyword">public</span> <span class="hljs-title">MyTransformation</span>(Context context) {
        <span class="hljs-keyword">super</span>(context);
    }

    <span class="hljs-annotation">@Override</span>
    <span class="hljs-keyword">protected</span> Bitmap <span class="hljs-title">transform</span>(BitmapPool pool, Bitmap toTransform, 
            <span class="hljs-keyword">int</span> outWidth, <span class="hljs-keyword">int</span> outHeight) {
       Bitmap myTransformedBitmap = ... <span class="hljs-comment">//对Bitmap进行各种变换处理。</span>
       <span class="hljs-keyword">return</span> myTransformedBitmap;
    }

    <span class="hljs-annotation">@Override</span>
    <span class="hljs-keyword">public</span> String <span class="hljs-title">getId</span>() {
        <span class="hljs-comment">// 返回代表该变换的唯一Id,会作为cache key的一部分。</span>
        <span class="hljs-comment">// 注意:最好不要用getClass().getName(),因为容易受混淆影响。如果变换过程不影响缓存数据,可以返回空字符串。</span>
        <span class="hljs-keyword">return</span> <span class="hljs-string">"com.example.myapp.MyTransformation"</span>;
    }
}</code><ul class="pre-numbering" style=""><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li></ul></pre>

<p>使用时只需使用<code>transform()</code>或<code>bitmapTransform()</code>方法即可:</p>

<pre class="prettyprint" name="code"><code class="language-java hljs  has-numbering">Glide.with(yourFragment)
    .load(yourUrl)
    .asBitmap()
    .transform(<span class="hljs-keyword">new</span> MyTransformation(context))
    .into(yourView);</code><ul class="pre-numbering" style=""><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul></pre>

<blockquote>
  <p>自定义图片处理时Glide会自动计算View/Target大小,我们不需要传View的宽高,当然你可以使用<code>override(int, int)</code>去改变这种行为。</p>
</blockquote>

<p>自定义图片处理时,为了避免创建大量Bitmap以及减少GC,可以考虑重用Bitmap,这就需要<code>BitmapPool</code>,典型地就是,从Bitmap池中拿一个Bitmap,用这个Bitmap生成一个Canvas, 然后在这个Canvas上画初始的Bitmap并使用Matrix、Paint、或者Shader处理这张图片。 <br>
为了有效并正确重用Bitmap需要遵循以下三条准则:</p>

<ol><li>永远不要把<code>transform()</code>传给你的原始resource或原始Bitmap给<code>recycle()</code>了,更不要放回<code>BitmapPool</code>,因为这些都自动完成了。值得注意的是,任何从<code>BitmapPool</code>取出的用于自定义图片变换的辅助Bitmap,如果不经过<code>transform()</code>方法返回,就必须主动放回<code>BitmapPool</code>或者调用<code>recycle()</code>回收。</li>
<li>如果你从BitmapPool拿出多个Bitmap或不使用你从BitmapPool拿出的一个Bitmap,一定要返回extras给BitmapPool。</li>
<li>如果你的图片处理没有替换原始resource(例如由于一张图片已经匹配了你想要的尺寸,你需要提前返回), transform()`方法就返回原始resource或原始Bitmap。 <br>
如:</li></ol>

<pre class="prettyprint" name="code"><code class="language-java hljs  has-numbering">    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyTransformation</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">BitmapTransformation</span> {</span>

        <span class="hljs-keyword">public</span> <span class="hljs-title">MyTransformation</span>(Context context) {
            <span class="hljs-keyword">super</span>(context);
        }

        <span class="hljs-annotation">@Override</span>
        <span class="hljs-keyword">protected</span> Bitmap <span class="hljs-title">transform</span>(BitmapPool pool, Bitmap toTransform, <span class="hljs-keyword">int</span> outWidth, <span class="hljs-keyword">int</span> outHeight) {
            Bitmap result = pool.get(outWidth, outHeight, Bitmap.Config.ARGB_8888);
            <span class="hljs-comment">// 如果BitmapPool中找不到符合该条件的Bitmap,get()方法会返回null,就需要我们自己创建Bitmap了</span>
            <span class="hljs-keyword">if</span> (result == <span class="hljs-keyword">null</span>) {
                <span class="hljs-comment">// 如果想让Bitmap支持透明度,就需要使用ARGB_8888</span>
                result = Bitmap.createBitmap(outWidth, outHeight, Bitmap.Config.ARGB_8888);
            }
            <span class="hljs-comment">//创建最终Bitmap的Canvas.</span>
            Canvas canvas = <span class="hljs-keyword">new</span> Canvas(result);
            Paint paint = <span class="hljs-keyword">new</span> Paint();
            paint.setAlpha(<span class="hljs-number">128</span>);
            <span class="hljs-comment">// 将原始Bitmap处理后画到最终Bitmap中</span>
            canvas.drawBitmap(toTransform, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, paint);
            <span class="hljs-comment">// 由于我们的图片处理替换了原始Bitmap,就return我们新的Bitmap就行。</span>
            <span class="hljs-comment">// Glide会自动帮我们回收原始Bitmap。</span>
            <span class="hljs-keyword">return</span> result;
        }

        <span class="hljs-annotation">@Override</span>
        <span class="hljs-keyword">public</span> String <span class="hljs-title">getId</span>() {
            <span class="hljs-comment">// Return some id that uniquely identifies your transformation.</span>
            <span class="hljs-keyword">return</span> <span class="hljs-string">"com.example.myapp.MyTransformation"</span>;
        }
    }</code><ul class="pre-numbering" style=""><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li><li>24</li><li>25</li><li>26</li><li>27</li><li>28</li><li>29</li><li>30</li><li>31</li></ul></pre>

<p>也可以直接实现<code>Transformation</code>接口,进行更灵活的图片处理,如进行简单地圆角处理:</p>

<pre class="prettyprint" name="code"><code class="language-java hljs  has-numbering"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RoundedCornersTransformation</span>  <span class="hljs-keyword">implements</span> <span class="hljs-title">Transformation</span><<span class="hljs-title">Bitmap</span>> {</span>

    <span class="hljs-keyword">private</span> BitmapPool mBitmapPool;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> mRadius;

    <span class="hljs-keyword">public</span> <span class="hljs-title">RoundedCornersTransformation</span>(Context context, <span class="hljs-keyword">int</span> mRadius) {
        <span class="hljs-keyword">this</span>(Glide.get(context).getBitmapPool(), mRadius);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-title">RoundedCornersTransformation</span>(BitmapPool mBitmapPool, <span class="hljs-keyword">int</span> mRadius) {
        <span class="hljs-keyword">this</span>.mBitmapPool = mBitmapPool;
        <span class="hljs-keyword">this</span>.mRadius = mRadius;
    }

    <span class="hljs-annotation">@Override</span>
    <span class="hljs-keyword">public</span> Resource<Bitmap> <span class="hljs-title">transform</span>(Resource<Bitmap> resource, <span class="hljs-keyword">int</span> outWidth, <span class="hljs-keyword">int</span> outHeight) {
        <span class="hljs-comment">//从其包装类中拿出Bitmap</span>
        Bitmap source = resource.get();
        <span class="hljs-keyword">int</span> width = source.getWidth();
        <span class="hljs-keyword">int</span> height = source.getHeight();
        Bitmap result = mBitmapPool.get(width, height, Bitmap.Config.ARGB_8888);
        <span class="hljs-keyword">if</span> (result == <span class="hljs-keyword">null</span>) {
            result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        }
        Canvas canvas = <span class="hljs-keyword">new</span> Canvas(result);
        <span class="hljs-comment">//以上已经算是教科书式写法了</span>
        Paint paint = <span class="hljs-keyword">new</span> Paint();
        paint.setAntiAlias(<span class="hljs-keyword">true</span>);
        paint.setShader(<span class="hljs-keyword">new</span> BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
        canvas.drawRoundRect(<span class="hljs-keyword">new</span> RectF(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, width, height), mRadius, mRadius, paint);
        <span class="hljs-comment">//返回包装成Resource的最终Bitmap</span>
        <span class="hljs-keyword">return</span> BitmapResource.obtain(result, mBitmapPool);
    }

    <span class="hljs-annotation">@Override</span>
    <span class="hljs-keyword">public</span> String <span class="hljs-title">getId</span>() {
        <span class="hljs-keyword">return</span> <span class="hljs-string">"RoundedTransformation(radius="</span> + mRadius + <span class="hljs-string">")"</span>;
    }
}</code><ul class="pre-numbering" style=""><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li><li>24</li><li>25</li><li>26</li><li>27</li><li>28</li><li>29</li><li>30</li><li>31</li><li>32</li><li>33</li><li>34</li><li>35</li><li>36</li><li>37</li><li>38</li><li>39</li></ul></pre></li>
<li><p>对请求状态进行监听:</p>

<pre class="prettyprint" name="code"><code class="language-java hljs  has-numbering"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MainActivity</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">AppCompatActivity</span> {</span>

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> String TAG = <span class="hljs-string">"MainActivity"</span>;

    <span class="hljs-keyword">private</span> ImageView iv_0;
    <span class="hljs-keyword">private</span> LoggingListener mCommonRequestListener;
    <span class="hljs-annotation">@Override</span>
    <span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onCreate</span>(Bundle savedInstanceState) {
        <span class="hljs-keyword">super</span>.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iv_0 = (ImageView) findViewById(R.id.iv_0);
        mCommonRequestListener = <span class="hljs-keyword">new</span> LoggingListener<String, GlideDrawable>();
        Glide
                .with(<span class="hljs-keyword">this</span>)
                .load(<span class="hljs-string">"http://inthecheesefactory.com/uploads/source/nestedfragment/fragments.png"</span>)
                .listener(mCommonRequestListener)
                .into(iv_0);
}
}</code><ul class="pre-numbering" style=""><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li></ul></pre>

<pre class="prettyprint" name="code"><code class="language-java hljs  has-numbering"><span class="hljs-javadoc">/**
*<span class="hljs-javadoctag"> @param</span> <A> model类型
*<span class="hljs-javadoctag"> @param</span> <B> resource类型
*/</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LoggingListener</span><<span class="hljs-title">A</span>, <span class="hljs-title">B</span>> <span class="hljs-keyword">implements</span> <span class="hljs-title">RequestListener</span><<span class="hljs-title">A</span>, <span class="hljs-title">B</span>> {</span>
<span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> level;
<span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> String name;
<span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> RequestListener<A, B> delegate;

<span class="hljs-keyword">public</span> <span class="hljs-title">LoggingListener</span>() {
    <span class="hljs-keyword">this</span>(<span class="hljs-string">""</span>);
}

<span class="hljs-keyword">public</span> <span class="hljs-title">LoggingListener</span>(@NonNull String name) {
    <span class="hljs-keyword">this</span>(Log.VERBOSE, name);
}

<span class="hljs-keyword">public</span> <span class="hljs-title">LoggingListener</span>(<span class="hljs-keyword">int</span> level, @NonNull String name) {
    <span class="hljs-keyword">this</span>(level, name, <span class="hljs-keyword">null</span>);
}

<span class="hljs-keyword">public</span> <span class="hljs-title">LoggingListener</span>(RequestListener<A, B> delegate) {
    <span class="hljs-keyword">this</span>(Log.VERBOSE, <span class="hljs-string">""</span>, delegate);
}

<span class="hljs-keyword">public</span> <span class="hljs-title">LoggingListener</span>(<span class="hljs-keyword">int</span> level, @NonNull String name, RequestListener<A, B> delegate) {
    <span class="hljs-keyword">this</span>.level = level;
    <span class="hljs-keyword">this</span>.name = name;
    <span class="hljs-keyword">this</span>.delegate = delegate == <span class="hljs-keyword">null</span> ? NoOpRequestListener.<A, B>get() : delegate;
}

<span class="hljs-annotation">@Override</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">onException</span>(Exception e, A model, Target<B> target, <span class="hljs-keyword">boolean</span> isFirstResource) {
    android.util.Log.println(level, <span class="hljs-string">"GLIDE"</span>, String.format(Locale.ROOT,
            <span class="hljs-string">"%s.onException(%s, %s, %s, %s)\n%s"</span>,
            name, e, model, strip(target), isFirst(isFirstResource), android.util.Log.getStackTraceString(e)));
    <span class="hljs-keyword">return</span> delegate.onException(e, model, target, isFirstResource);
}

<span class="hljs-annotation">@Override</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">onResourceReady</span>(B resource, A model, Target<B> target, <span class="hljs-keyword">boolean</span> isFromMemoryCache,
                               <span class="hljs-keyword">boolean</span> isFirstResource) {
    String resourceString = strip(getResourceDescription(resource));
    String targetString = strip(getTargetDescription(target));
    android.util.Log.println(level, <span class="hljs-string">"GLIDE"</span>, String.format(Locale.ROOT,
            <span class="hljs-string">"%s.onResourceReady(%s, %s, %s, %s, %s)"</span>,
            name, resourceString, model, targetString, isMem(isFromMemoryCache), isFirst(isFirstResource)));
    <span class="hljs-keyword">return</span> delegate.onResourceReady(resource, model, target, isFromMemoryCache, isFirstResource);
}

<span class="hljs-keyword">private</span> String <span class="hljs-title">isMem</span>(<span class="hljs-keyword">boolean</span> isFromMemoryCache) {
    <span class="hljs-keyword">return</span> isFromMemoryCache ? <span class="hljs-string">"sync"</span> : <span class="hljs-string">"async"</span>;
}

<span class="hljs-keyword">private</span> String <span class="hljs-title">isFirst</span>(<span class="hljs-keyword">boolean</span> isFirstResource) {
    <span class="hljs-keyword">return</span> isFirstResource ? <span class="hljs-string">"first"</span> : <span class="hljs-string">"not first"</span>;
}

<span class="hljs-keyword">private</span> String <span class="hljs-title">getTargetDescription</span>(Target<B> target) {
    String result;
    <span class="hljs-keyword">if</span> (target <span class="hljs-keyword">instanceof</span> ViewTarget) {
        View v = ((ViewTarget) target).getView();
        LayoutParams p = v.getLayoutParams();
        result = String.format(Locale.ROOT,
                <span class="hljs-string">"%s(params=%dx%d->size=%dx%d)"</span>, target, p.width, p.height, v.getWidth(), v.getHeight());
    } <span class="hljs-keyword">else</span> {
        result = String.valueOf(target);
    }
    <span class="hljs-keyword">return</span> result;
}

<span class="hljs-keyword">private</span> String <span class="hljs-title">getResourceDescription</span>(B resource) {
    String result;
    <span class="hljs-keyword">if</span> (resource <span class="hljs-keyword">instanceof</span> Bitmap) {
        Bitmap bm = (Bitmap) resource;
        result = String.format(Locale.ROOT,
                <span class="hljs-string">"%s(%dx%d@%s)"</span>, resource, bm.getWidth(), bm.getHeight(), bm.getConfig());
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (resource <span class="hljs-keyword">instanceof</span> BitmapDrawable) {
        Bitmap bm = ((BitmapDrawable) resource).getBitmap();
        result = String.format(Locale.ROOT,
                <span class="hljs-string">"%s(%dx%d@%s)"</span>, resource, bm.getWidth(), bm.getHeight(), bm.getConfig());
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (resource <span class="hljs-keyword">instanceof</span> GlideBitmapDrawable) {
        Bitmap bm = ((GlideBitmapDrawable) resource).getBitmap();
        result = String.format(Locale.ROOT,
                <span class="hljs-string">"%s(%dx%d@%s)"</span>, resource, bm.getWidth(), bm.getHeight(), bm.getConfig());
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (resource <span class="hljs-keyword">instanceof</span> Drawable) {
        Drawable d = (Drawable) resource;
        result = String.format(Locale.ROOT,
                <span class="hljs-string">"%s(%dx%d)"</span>, resource, d.getIntrinsicWidth(), d.getIntrinsicHeight());
    } <span class="hljs-keyword">else</span> {
        result = String.valueOf(resource);
    }
    <span class="hljs-keyword">return</span> result;
}

<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> String <span class="hljs-title">strip</span>(Object text) {
    <span class="hljs-keyword">return</span> String.valueOf(text).replaceAll(<span class="hljs-string">"(com|android|net|org)(\\.[a-z]+)+\\."</span>, <span class="hljs-string">""</span>);
}
}</code><ul class="pre-numbering" style=""><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li><li>24</li><li>25</li><li>26</li><li>27</li><li>28</li><li>29</li><li>30</li><li>31</li><li>32</li><li>33</li><li>34</li><li>35</li><li>36</li><li>37</li><li>38</li><li>39</li><li>40</li><li>41</li><li>42</li><li>43</li><li>44</li><li>45</li><li>46</li><li>47</li><li>48</li><li>49</li><li>50</li><li>51</li><li>52</li><li>53</li><li>54</li><li>55</li><li>56</li><li>57</li><li>58</li><li>59</li><li>60</li><li>61</li><li>62</li><li>63</li><li>64</li><li>65</li><li>66</li><li>67</li><li>68</li><li>69</li><li>70</li><li>71</li><li>72</li><li>73</li><li>74</li><li>75</li><li>76</li><li>77</li><li>78</li><li>79</li><li>80</li><li>81</li><li>82</li><li>83</li><li>84</li><li>85</li><li>86</li><li>87</li><li>88</li><li>89</li><li>90</li><li>91</li><li>92</li><li>93</li><li>94</li><li>95</li><li>96</li><li>97</li><li>98</li><li>99</li></ul></pre>

<pre class="prettyprint" name="code"><code class="language-java hljs  has-numbering"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NoOpRequestListener</span><<span class="hljs-title">A</span>, <span class="hljs-title">B</span>> <span class="hljs-keyword">implements</span> <span class="hljs-title">RequestListener</span><<span class="hljs-title">A</span>, <span class="hljs-title">B</span>> {</span>
<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> RequestListener INSTANCE = <span class="hljs-keyword">new</span> NoOpRequestListener();

<span class="hljs-annotation">@SuppressWarnings</span>(<span class="hljs-string">"unchecked"</span>)
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <A, B> RequestListener<A, B> <span class="hljs-title">get</span>() {
    <span class="hljs-keyword">return</span> INSTANCE;
}

<span class="hljs-keyword">private</span> <span class="hljs-title">NoOpRequestListener</span>() {
}

<span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">onException</span>(Exception e, A a, Target<B> target, <span class="hljs-keyword">boolean</span> b) {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
}
<span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">onResourceReady</span>(B b, A a, Target<B> target, <span class="hljs-keyword">boolean</span> b2, <span class="hljs-keyword">boolean</span> b1) {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
}
}</code><ul class="pre-numbering" style=""><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li></ul></pre>

<p>通过GenericRequestBuilder的<code>listener()</code>方法添加一个<code>RequestListener</code>实现,但要注意,最好不要用匿名类,也不要每次都创建新的监听器,要使用单例进行统一监听处理,以避免不必要的内存申请和不必要的引用。方法最好返回false,以便Glide能继续进行后续处理(如显示error占位符)。</p></li>
<li>对资源的下载进度进行监听: <br>
可以借助OkHttp的拦截器进行进度监听。OkHttp的拦截器官方Sample请移步<a href="https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/Progress.java" target="_blank">这里</a>。我们可以利用这个拦截器进行监听并处理,需要自定义ModelLoader和DataFetcher,具体请详见我的Git:<a href="https://github.com/shangmingchao/ProgressGlide" target="_blank">https://github.com/shangmingchao/ProgressGlide</a>,欢迎Star啊,不过没有太大必要告诉用户图片加载的进度(sjudd和TWiStErRob他们说的)。同时也可以看一下TWiStErRob大神的<a href="https://gist.github.com/TWiStErRob/08d5807e396740e52c90" target="_blank">实现</a>(自备梯子哈~.~)。</li>
</ol>



<h3 id="四-glide有哪些坑"><a name="t8" target="_blank"></a><strong>四. Glide有哪些“坑”?</strong></h3>

<ol>
<li><strong>ImageView的setTag问题</strong> <br>
<strong>问题描述:</strong>如果使用<code>Glide</code>的<code>into(imageView)</code>为ImageView设置图片的同时使用ImageView的<code>setTag(final Object tag)</code>方法,将会导致<code>java.lang.IllegalArgumentException: You must not call setTag() on a view Glide is targeting</code>异常。因为<code>Glide</code>的<code>ViewTarget</code>中通过<code>view.setTag(tag)</code>和<code>view.getTag()</code>标记请求的,由于Android 4.0之前Tag存储在静态map里,如果Glide使用<code>setTag(int key, final Object tag)</code>方法标记请求则可能会导致内存泄露,所以Glide默认使用<code>view.setTag(tag)</code>标记请求,你就不能重复调用了。 <br>
<strong>解决办法:</strong>如果你需要为ImageView设置Tag,<strong>必须</strong>使用<code>setTag(int key, final Object tag)</code>及<code>getTag(int key)</code>方法,其中key必须是合法的资源ID以确保key的唯一性,典型做法就是在资源文件中声明type="id"的item资源。</li>
<li><strong>placeholder()导致的图片变形问题</strong> <br>
<strong>问题描述:</strong>使用<code>.placeholder()</code>方法在某些情况下会导致图片显示的时候出现图片变形的情况。这是因为Glide默认开启的crossFade动画导致的TransitionDrawable绘制异常,详细描述和讨论可以看一下这个<a href="https://github.com/bumptech/glide/issues/363" target="_blank">#363</a> issue。根本原因就是你的placeholder图片和你要加载显示的图片宽高比不一样,而Android的TransitionDrawable无法很好地处理不同宽高比的过渡问题,这的确是个Bug,是Android的也是Glide的。 <br>
<strong>解决办法:</strong>使用.dontAnimate()方法禁用过渡动画,或者使用animate()方法自己写动画,再或者自己修复TransitionDrawable的问题。</li>
<li><p><strong>ImageView的资源回收问题</strong> <br>
<strong>问题描述:</strong>默认情况下,Glide会根据<code>with()</code>使用的Activity或Fragment的生命周期自动调整资源请求以及资源回收。但是如果有很占内存的Fragment或Activity不销毁而仅仅是隐藏视图,那么这些图片资源就没办法及时回收,即使是GC的时候。 <br>
<strong>解决办法:</strong>可以考虑使用<code>WeakReference</code>,如:</p>

<pre class="prettyprint" name="code"><code class="language-java hljs  has-numbering">    <span class="hljs-keyword">final</span> WeakReference<ImageView> imageViewWeakReference = <span class="hljs-keyword">new</span> WeakReference<>(imageView);
    ImageView target = imageViewWeakReference.get();
    <span class="hljs-keyword">if</span> (target != <span class="hljs-keyword">null</span>) {
        Glide.with(context).load(uri).into(target);
    }</code><ul class="pre-numbering" style=""><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul></pre></li>
<li><strong>ImageView的scaleType问题</strong> <br>
<code>scaleType</code>默认为<code>fitCenter</code>模式,如果你想设置成<code>centerInside</code>,不好意思,3.x还没有这个方法,参见这个<a href="https://github.com/bumptech/glide/issues/591" target="_blank">#591</a> issue,折中的解决办法就是放弃使用<code>centerInside</code>,或者结合<code>android:scaleType="centerInside"</code>和<code>.dontTransform()</code>使用以禁止Glide对资源进行转换。 <br>
如果你想要ImageView的宽高根据图片资源的大小而定(即使用<code>wrap_comtent</code>),那么你就必须明确告诉Glide我想加载原始资源:使用<code>android:scaleType="center"</code>,或者<code>.dontTransform()</code>,或者<code>.override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)</code>。 <br>
不推荐使用<code>fitXY</code>,因为这样Glide会加载全尺寸图像到内存中而造成不必要的内存占用。</li>
<li><p><strong>异步线程完成后加载图片的崩溃问题</strong> <br>
<strong>问题描述:</strong>通常情况下,异步线程会被约束在Activity生命周期内,所以异步线程完成后使用Glide加载图片是没有问题的。但如果你的异步线程在Activity销毁时没有取消掉,那么异步线程完成后就Glide就无法为一个已销毁的Activity加载图片资源,抛出的异常如下(在with()方法中就进行判断并抛出异常):</p>

<pre class="prettyprint" name="code"><code class="hljs avrasm has-numbering"><span class="hljs-label">java.lang.IllegalArgumentException:</span> You cannot start a load for a destroyed activity
    at <span class="hljs-keyword">com</span><span class="hljs-preprocessor">.bumptech</span><span class="hljs-preprocessor">.glide</span><span class="hljs-preprocessor">.manager</span><span class="hljs-preprocessor">.RequestManagerRetriever</span><span class="hljs-preprocessor">.assertNotDestroyed</span>(RequestManagerRetriever<span class="hljs-preprocessor">.java</span>:<span class="hljs-number">134</span>)
    at <span class="hljs-keyword">com</span><span class="hljs-preprocessor">.bumptech</span><span class="hljs-preprocessor">.glide</span><span class="hljs-preprocessor">.manager</span><span class="hljs-preprocessor">.RequestManagerRetriever</span><span class="hljs-preprocessor">.get</span>(RequestManagerRetriever<span class="hljs-preprocessor">.java</span>:<span class="hljs-number">102</span>)
    at <span class="hljs-keyword">com</span><span class="hljs-preprocessor">.bumptech</span><span class="hljs-preprocessor">.glide</span><span class="hljs-preprocessor">.Glide</span><span class="hljs-preprocessor">.with</span>(Glide<span class="hljs-preprocessor">.java</span>:<span class="hljs-number">653</span>)
    at <span class="hljs-keyword">com</span><span class="hljs-preprocessor">.frank</span><span class="hljs-preprocessor">.glidedemo</span><span class="hljs-preprocessor">.TestActivity</span><span class="hljs-preprocessor">.onGetDataCompleted</span>(TestActivity<span class="hljs-preprocessor">.java</span>:<span class="hljs-number">23</span>)
    at <span class="hljs-keyword">com</span><span class="hljs-preprocessor">.frank</span><span class="hljs-preprocessor">.glidedemo</span><span class="hljs-preprocessor">.TestActivity</span><span class="hljs-preprocessor">.access</span>$000(TestActivity<span class="hljs-preprocessor">.java</span>:<span class="hljs-number">10</span>)
    at <span class="hljs-keyword">com</span><span class="hljs-preprocessor">.frank</span><span class="hljs-preprocessor">.glidedemo</span><span class="hljs-preprocessor">.TestActivity</span>$BackgroundTask<span class="hljs-preprocessor">.onPostExecute</span>(TestActivity<span class="hljs-preprocessor">.java</span>:<span class="hljs-number">46</span>)
    at <span class="hljs-keyword">com</span><span class="hljs-preprocessor">.frank</span><span class="hljs-preprocessor">.glidedemo</span><span class="hljs-preprocessor">.TestActivity</span>$BackgroundTask<span class="hljs-preprocessor">.onPostExecute</span>(TestActivity<span class="hljs-preprocessor">.java</span>:<span class="hljs-number">28</span>)
    at android<span class="hljs-preprocessor">.os</span><span class="hljs-preprocessor">.AsyncTask</span><span class="hljs-preprocessor">.finish</span>(AsyncTask<span class="hljs-preprocessor">.java</span>:<span class="hljs-number">632</span>)
    at android<span class="hljs-preprocessor">.os</span><span class="hljs-preprocessor">.AsyncTask</span><span class="hljs-preprocessor">.access</span>$600(AsyncTask<span class="hljs-preprocessor">.java</span>:<span class="hljs-number">177</span>)
    at android<span class="hljs-preprocessor">.os</span><span class="hljs-preprocessor">.AsyncTask</span>$InternalHandler<span class="hljs-preprocessor">.handleMessage</span>(AsyncTask<span class="hljs-preprocessor">.java</span>:<span class="hljs-number">645</span>)
    at android<span class="hljs-preprocessor">.os</span><span class="hljs-preprocessor">.Handler</span><span class="hljs-preprocessor">.dispatchMessage</span>(Handler<span class="hljs-preprocessor">.java</span>:<span class="hljs-number">102</span>)
    at android<span class="hljs-preprocessor">.os</span><span class="hljs-preprocessor">.Looper</span><span class="hljs-preprocessor">.loop</span>(Looper<span class="hljs-preprocessor">.java</span>:<span class="hljs-number">157</span>)
    at android<span class="hljs-preprocessor">.app</span><span class="hljs-preprocessor">.ActivityThread</span><span class="hljs-preprocessor">.main</span>(ActivityThread<span class="hljs-preprocessor">.java</span>:<span class="hljs-number">5356</span>)
    at java<span class="hljs-preprocessor">.lang</span><span class="hljs-preprocessor">.reflect</span><span class="hljs-preprocessor">.Method</span><span class="hljs-preprocessor">.invokeNative</span>(Native Method)
    at java<span class="hljs-preprocessor">.lang</span><span class="hljs-preprocessor">.reflect</span><span class="hljs-preprocessor">.Method</span><span class="hljs-preprocessor">.invoke</span>(Method<span class="hljs-preprocessor">.java</span>:<span class="hljs-number">515</span>)
    at <span class="hljs-keyword">com</span><span class="hljs-preprocessor">.android</span><span class="hljs-preprocessor">.internal</span><span class="hljs-preprocessor">.os</span><span class="hljs-preprocessor">.ZygoteInit</span>$MethodAndArgsCaller<span class="hljs-preprocessor">.run</span>(ZygoteInit<span class="hljs-preprocessor">.java</span>:<span class="hljs-number">1265</span>)
    at <span class="hljs-keyword">com</span><span class="hljs-preprocessor">.android</span><span class="hljs-preprocessor">.internal</span><span class="hljs-preprocessor">.os</span><span class="hljs-preprocessor">.ZygoteInit</span><span class="hljs-preprocessor">.main</span>(ZygoteInit<span class="hljs-preprocessor">.java</span>:<span class="hljs-number">1081</span>)
    at dalvik<span class="hljs-preprocessor">.system</span><span class="hljs-preprocessor">.NativeStart</span><span class="hljs-preprocessor">.main</span>(Native Method)
    }</code><ul class="pre-numbering" style=""><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li></ul></pre>

<p><strong>解决办法:</strong>正确管理Background Threads(异步线程),当Activity停止或销毁时,停止所有相关的异步线程,停止所有后续的UI操作。或者加载前使用<code>isFinishing()</code>或<code>isDestroyed()</code>进行限制(不建议这种处理方式)。</p></li>
<li><strong>由于Bitmap复用导致的在某些设备上图片错乱的问题</strong> <br>
<strong>问题描述:</strong> Glide默认使用BitmapPool的方式对应用中用到的Bitmap进行复用,以减少频繁的内存申请和内存回收,而且默认使用的Bitmap模式为RGB565以减少内存开销。但在某些设备上(通常在Galaxy系列5.X设备上很容易复现)某些情况下会出现图片加载错乱的问题,具体详见这个<a href="https://github.com/bumptech/glide/issues/601" target="_blank">#601</a> issue。原因初步确定是OpenGL纹理渲染异常。 <br>
<strong>解决办法:</strong><code>GlideModule</code>使用<code>PREFER_ARGB_8888</code>(Glide4.X已经默认使用该模式了),虽然内存占用比RGB565更多一点,但可以更好地处理有透明度Bitmap的复用问题。或者禁用Bitmap复用<code>setBitmapPool(new BitmapPoolAdapter())</code>来修复这个问题(不推荐这种处理方式)。</li>
</ol>

<hr>

<p>想了解更多,可以看一下这几篇翻译:</p>

<ul>
<li><a href="http://blog.csdn.net/shangmingchao/article/details/78219558" target="_blank">Glide v4详解</a></li>
<li><a href="http://blog.csdn.net/shangmingchao/article/details/51172972" target="_blank">Glide使用详解(二)</a></li>
<li><a href="http://blog.csdn.net/shangmingchao/article/details/51026742" target="_blank">Glide之GlideModule</a></li>
<li><a href="http://blog.csdn.net/shangmingchao/article/details/51038529" target="_blank">Glide之Target</a></li>
<li><a href="http://blog.csdn.net/shangmingchao/article/details/51058785" target="_blank">Glide之后台线程加载及缓存资源</a></li>
</ul></div>
        <script type="text/javascript">
            $(function () {
                $('pre.prettyprint code').each(function () {
                    var lines = $(this).text().split('\n').length;
                    var $numbering = $('<ul/>').addClass('pre-numbering').hide();
                    $(this).addClass('has-numbering').parent().append($numbering);
                    for (i = 1; i <= lines; i++) {
                        $numbering.append($('<li/>').text(i));
                    };
                    $numbering.fadeIn(1700);
                });
            });
        </script>
   
</div>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值