GlideNewDemo【Glide4.7.1版本的簡單使用以及圓角功能】

版權聲明:本文爲HaiyuKing原創文章,轉載請註明出處!html

前言

簡單記錄下Glide4.7.1版本的使用和實現圓角方案。java

注意:關於詳細使用請仔細閱讀《官方指南》。android

效果圖

使用步驟

1、項目組織結構圖

注意事項:git

一、  導入類文件後須要change包名以及從新import R文件路徑github

二、  Values目錄下的文件(strings.xml、dimens.xml、colors.xml等),若是項目中存在,則複製裏面的內容,不要整個覆蓋算法

2、導入步驟

(1)在APP的build.gradle中添加Glide依賴

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.why.project.glidenewdemo"
        minSdkVersion 16
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
//glide
repositories { mavenCentral() maven { url 'https://maven.google.com' } }
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    //glide
    compile 'com.github.bumptech.glide:glide:4.7.1'
    //添加對 Glide 的註解和註解解析器的依賴
    annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1'
    //添加一個對 OkHttp 集成庫的依賴
    compile "com.github.bumptech.glide:okhttp3-integration:4.7.1"
}

官方指南資料canvas

至於集成OkHttp3等網絡庫請參考官網資料api

(2)在AndroidManifest.xml中添加權限【根據實際狀況進行添加,有些權限須要申請運行時權限】

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.why.project.glidenewdemo">

    <!-- Glide -->
    <!--若是你計劃從 URL 或一個網絡鏈接中加載數據,你須要添加 INTERNET 和 ACCESS_NETWORK_STATE 權限-->
    <uses-permission android:name="android.permission.INTERNET"/>
    <!--若是你正在從 URL 加載圖片,Glide 能夠自動幫助你處理片狀網絡鏈接:它能夠監聽用戶的鏈接狀態並在用戶從新鏈接到網絡時重啓以前失敗的請求。 若是 Glide 檢測到你的應用擁有 ACCESS_NETWORK_STATE 權限,Glide 將自動監聽鏈接狀態而不須要額外的改動。-->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <!--要從本地文件夾或 DCIM 或圖庫中加載圖片,你將須要添加 READ_EXTERNAL_STORAGE 權限-->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <!--而若是要將 Glide 的緩存存儲到公有 SD 卡上,你還須要添加 WRITE_EXTERNAL_STORAGE 權限-->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

(3)添加自定義GlideModule子類(包名必須是com.example.myapp),設置內存緩存、Bitmap 池、磁盤緩存、默認請求選項(出於我的習慣,沒有設置)解碼格式等等

package com.example.myapp;

import android.content.Context;

import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.bitmap_recycle.LruBitmapPool;
import com.bumptech.glide.load.engine.cache.LruResourceCache;
import com.bumptech.glide.load.engine.cache.MemorySizeCalculator;
import com.bumptech.glide.module.AppGlideModule;
import com.bumptech.glide.request.RequestOptions;

/**
 * Created by HaiyuKing
 * Used 自定義GlideModule子類,設置內存緩存、Bitmap 池、磁盤緩存、、默認請求選項、解碼格式等等
 * https://muyangmin.github.io/glide-docs-cn/doc/configuration.html#avoid-appglidemodule-in-libraries
 */
@GlideModule
public final class MyAppGlideModule extends AppGlideModule {

    int diskCacheSize = 1024 * 1024 * 200; // 200mb
    int memorySize = (int) (Runtime.getRuntime().maxMemory()) / 8;  // 取1/8最大內存做爲最大緩存


    @Override
    public void applyOptions(Context context, GlideBuilder builder) {
        //設置解碼格式
        /*在 Glide v3, 默認的 DecodeFormat 是 DecodeFormat.PREFER_RGB_565,它將使用 [Bitmap.Config.RGB_565],除非圖片包含或可能包含透明像素。對於給定的圖片尺寸,RGB_565 只使用 [Bitmap.Config.ARGB_8888] 一半的內存,但對於特定的圖片有明顯的畫質問題,包括條紋(banding)和着色(tinting)。
        爲了不RGB_565的畫質問題,Glide 如今默認使用 ARGB_8888。結果是,圖片質量變高了,但內存使用也增長了。*/
        builder.setDefaultRequestOptions(new RequestOptions().format(DecodeFormat.PREFER_RGB_565));

        //默認請求選項【不太習慣,仍是每一個請求重複使用吧】
        /*builder.setDefaultRequestOptions(
                new RequestOptions()
                        //設置等待時的圖片
                        .placeholder(R.drawable.img_loading)
                        //設置加載失敗後的圖片顯示
                        .error(R.drawable.img_error)
                        .centerCrop()
                        //緩存策略,跳過內存緩存【此處應該設置爲false,不然列表刷新時會閃一下】
                        .skipMemoryCache(false)
                        //緩存策略,貌似只有這一個設置
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        //設置圖片加載的優先級
                        .priority(Priority.HIGH));*/

        // 設置內存緩存
        MemorySizeCalculator calculator = new MemorySizeCalculator.Builder(context)
                .setMemoryCacheScreens(2)
                .build();
        builder.setMemoryCache(new LruResourceCache(calculator.getMemoryCacheSize()));
        //builder.setMemoryCache(new LruResourceCache(memorySize));//自定義大小

        //設置Bitmap 池
        MemorySizeCalculator calculator2 = new MemorySizeCalculator.Builder(context)
                .setBitmapPoolScreens(3)
                .build();
        builder.setBitmapPool(new LruBitmapPool(calculator2.getBitmapPoolSize()));
        //builder.setBitmapPool(new LruBitmapPool(memorySize));//自定義大小

        //設置磁盤緩存【暫時不作處理】
        //lide 使用 DiskLruCacheWrapper 做爲默認的 磁盤緩存 。 DiskLruCacheWrapper 是一個使用 LRU 算法的固定大小的磁盤緩存。默認磁盤大小爲 250 MB ,位置是在應用的 緩存文件夾 中的一個 特定目錄 。
        /*builder.setDiskCache(new ExternalDiskCacheFactory(context));
        builder.setDiskCache(new InternalDiskCacheFactory(context, diskCacheSize));*/
    }
}

而後Rebuid Project緩存

 參考《配置網絡

官方指南資料

 

(4)將glide包(實現圓角方案)複製到項目中【參考Glide Transformations進行修改】

package com.glide;

import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.support.annotation.NonNull;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;

import java.security.MessageDigest;

/**
 * Created by HaiyuKing
 * Create Date 2018/7/29 17:54
 * Used
 */

public class RoundedCornersTransformation extends BitmapTransformation {

    private static final int VERSION = 1;
    private static final String ID = "jp.wasabeef.glide.transformations.RoundedCornersTransformation." + VERSION;


    public enum CornerType {
        ALL,
        TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT,
        TOP, BOTTOM, LEFT, RIGHT,
        OTHER_TOP_LEFT, OTHER_TOP_RIGHT, OTHER_BOTTOM_LEFT, OTHER_BOTTOM_RIGHT,
        DIAGONAL_FROM_TOP_LEFT, DIAGONAL_FROM_TOP_RIGHT
    }

    private int radius;
    private int diameter;
    private int margin;
    private CornerType cornerType;

    public RoundedCornersTransformation(int radius, int margin) {
        this(radius, margin, CornerType.ALL);
    }

    public RoundedCornersTransformation(int radius, int margin, CornerType cornerType) {
        this.radius = radius;
        this.diameter = this.radius * 2;
        this.margin = margin;
        this.cornerType = cornerType;
    }

    @Override
    protected Bitmap transform(@NonNull BitmapPool pool,
                                         @NonNull Bitmap toTransform, int outWidth, int outHeight) {
        int width = toTransform.getWidth();
        int height = toTransform.getHeight();

        Bitmap bitmap = pool.get(width, height, Bitmap.Config.ARGB_8888);
        bitmap.setHasAlpha(true);

        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setShader(new BitmapShader(toTransform, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
        drawRoundRect(canvas, paint, width, height);
        return bitmap;
    }

    private void drawRoundRect(Canvas canvas, Paint paint, float width, float height) {
        float right = width - margin;
        float bottom = height - margin;

        switch (cornerType) {
            case ALL:
                canvas.drawRoundRect(new RectF(margin, margin, right, bottom), radius, radius, paint);
                break;
            case TOP_LEFT:
                drawTopLeftRoundRect(canvas, paint, right, bottom);
                break;
            case TOP_RIGHT:
                drawTopRightRoundRect(canvas, paint, right, bottom);
                break;
            case BOTTOM_LEFT:
                drawBottomLeftRoundRect(canvas, paint, right, bottom);
                break;
            case BOTTOM_RIGHT:
                drawBottomRightRoundRect(canvas, paint, right, bottom);
                break;
            case TOP:
                drawTopRoundRect(canvas, paint, right, bottom);
                break;
            case BOTTOM:
                drawBottomRoundRect(canvas, paint, right, bottom);
                break;
            case LEFT:
                drawLeftRoundRect(canvas, paint, right, bottom);
                break;
            case RIGHT:
                drawRightRoundRect(canvas, paint, right, bottom);
                break;
            case OTHER_TOP_LEFT:
                drawOtherTopLeftRoundRect(canvas, paint, right, bottom);
                break;
            case OTHER_TOP_RIGHT:
                drawOtherTopRightRoundRect(canvas, paint, right, bottom);
                break;
            case OTHER_BOTTOM_LEFT:
                drawOtherBottomLeftRoundRect(canvas, paint, right, bottom);
                break;
            case OTHER_BOTTOM_RIGHT:
                drawOtherBottomRightRoundRect(canvas, paint, right, bottom);
                break;
            case DIAGONAL_FROM_TOP_LEFT:
                drawDiagonalFromTopLeftRoundRect(canvas, paint, right, bottom);
                break;
            case DIAGONAL_FROM_TOP_RIGHT:
                drawDiagonalFromTopRightRoundRect(canvas, paint, right, bottom);
                break;
            default:
                canvas.drawRoundRect(new RectF(margin, margin, right, bottom), radius, radius, paint);
                break;
        }
    }

    private void drawTopLeftRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(margin, margin, margin + diameter, margin + diameter), radius,
                radius, paint);
        canvas.drawRect(new RectF(margin, margin + radius, margin + radius, bottom), paint);
        canvas.drawRect(new RectF(margin + radius, margin, right, bottom), paint);
    }

    private void drawTopRightRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(right - diameter, margin, right, margin + diameter), radius,
                radius, paint);
        canvas.drawRect(new RectF(margin, margin, right - radius, bottom), paint);
        canvas.drawRect(new RectF(right - radius, margin + radius, right, bottom), paint);
    }

    private void drawBottomLeftRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(margin, bottom - diameter, margin + diameter, bottom), radius,
                radius, paint);
        canvas.drawRect(new RectF(margin, margin, margin + diameter, bottom - radius), paint);
        canvas.drawRect(new RectF(margin + radius, margin, right, bottom), paint);
    }

    private void drawBottomRightRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(right - diameter, bottom - diameter, right, bottom), radius,
                radius, paint);
        canvas.drawRect(new RectF(margin, margin, right - radius, bottom), paint);
        canvas.drawRect(new RectF(right - radius, margin, right, bottom - radius), paint);
    }

    private void drawTopRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(margin, margin, right, margin + diameter), radius, radius,
                paint);
        canvas.drawRect(new RectF(margin, margin + radius, right, bottom), paint);
    }

    private void drawBottomRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(margin, bottom - diameter, right, bottom), radius, radius,
                paint);
        canvas.drawRect(new RectF(margin, margin, right, bottom - radius), paint);
    }

    private void drawLeftRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(margin, margin, margin + diameter, bottom), radius, radius,
                paint);
        canvas.drawRect(new RectF(margin + radius, margin, right, bottom), paint);
    }

    private void drawRightRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(right - diameter, margin, right, bottom), radius, radius, paint);
        canvas.drawRect(new RectF(margin, margin, right - radius, bottom), paint);
    }

    private void drawOtherTopLeftRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(margin, bottom - diameter, right, bottom), radius, radius,
                paint);
        canvas.drawRoundRect(new RectF(right - diameter, margin, right, bottom), radius, radius, paint);
        canvas.drawRect(new RectF(margin, margin, right - radius, bottom - radius), paint);
    }

    private void drawOtherTopRightRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(margin, margin, margin + diameter, bottom), radius, radius,
                paint);
        canvas.drawRoundRect(new RectF(margin, bottom - diameter, right, bottom), radius, radius,
                paint);
        canvas.drawRect(new RectF(margin + radius, margin, right, bottom - radius), paint);
    }

    private void drawOtherBottomLeftRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(margin, margin, right, margin + diameter), radius, radius,
                paint);
        canvas.drawRoundRect(new RectF(right - diameter, margin, right, bottom), radius, radius, paint);
        canvas.drawRect(new RectF(margin, margin + radius, right - radius, bottom), paint);
    }

    private void drawOtherBottomRightRoundRect(Canvas canvas, Paint paint, float right,
                                               float bottom) {
        canvas.drawRoundRect(new RectF(margin, margin, right, margin + diameter), radius, radius,
                paint);
        canvas.drawRoundRect(new RectF(margin, margin, margin + diameter, bottom), radius, radius,
                paint);
        canvas.drawRect(new RectF(margin + radius, margin + radius, right, bottom), paint);
    }

    private void drawDiagonalFromTopLeftRoundRect(Canvas canvas, Paint paint, float right,
                                                  float bottom) {
        canvas.drawRoundRect(new RectF(margin, margin, margin + diameter, margin + diameter), radius,
                radius, paint);
        canvas.drawRoundRect(new RectF(right - diameter, bottom - diameter, right, bottom), radius,
                radius, paint);
        canvas.drawRect(new RectF(margin, margin + radius, right - diameter, bottom), paint);
        canvas.drawRect(new RectF(margin + diameter, margin, right, bottom - radius), paint);
    }

    private void drawDiagonalFromTopRightRoundRect(Canvas canvas, Paint paint, float right,
                                                   float bottom) {
        canvas.drawRoundRect(new RectF(right - diameter, margin, right, margin + diameter), radius,
                radius, paint);
        canvas.drawRoundRect(new RectF(margin, bottom - diameter, margin + diameter, bottom), radius,
                radius, paint);
        canvas.drawRect(new RectF(margin, margin, right - radius, bottom - radius), paint);
        canvas.drawRect(new RectF(margin + radius, margin + radius, right, bottom), paint);
    }

    @Override public String toString() {
        return "RoundedTransformation(radius=" + radius + ", margin=" + margin + ", diameter="
                + diameter + ", cornerType=" + cornerType.name() + ")";
    }

    @Override public boolean equals(Object o) {
        return o instanceof RoundedCornersTransformation &&
                ((RoundedCornersTransformation) o).radius == radius &&
                ((RoundedCornersTransformation) o).diameter == diameter &&
                ((RoundedCornersTransformation) o).margin == margin &&
                ((RoundedCornersTransformation) o).cornerType == cornerType;
    }

    @Override public int hashCode() {
        return ID.hashCode() + radius * 10000 + diameter * 1000 + margin * 100 + cornerType.ordinal() * 10;
    }

    @Override public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
        messageDigest.update((ID + radius + diameter + margin + cornerType).getBytes(CHARSET));
    }
}
RoundedCornersTransformation.java

3、使用方法

若是使用了 Generated API,那麼相對比Glide3.7.0,使用方法幾乎相似,個別屬性設置須要修改

Glide3.7.0的代碼:

Glide.with(mContext)
                .load(imgUrl)
                //設置等待時的圖片
                .placeholder(R.drawable.img_loading)
                //設置加載失敗後的圖片顯示
                .error(R.drawable.img_error)
                .fitCenter()
                //默認淡入淡出動畫
                .crossFade()
                //緩存策略,跳過內存緩存【此處應該設置爲false,不然列表刷新時會閃一下】
                .skipMemoryCache(false)
                //緩存策略,硬盤緩存-僅僅緩存最終的圖像,即下降分辨率後的(或者是轉換後的)
                .diskCacheStrategy(DiskCacheStrategy.RESULT)
                //設置圖片加載的優先級
                .priority(Priority.HIGH)
                .into(mImgBase);

Glide4.7.1的代碼:

GlideApp.with(mContext)
                .load(imgUrl)
                //設置等待時的圖片
                .placeholder(R.drawable.img_loading)
                //設置加載失敗後的圖片顯示
                .error(R.drawable.img_error)
                .fitCenter()
                //默認淡入淡出動畫
                .transition(withCrossFade())
                //緩存策略,跳過內存緩存【此處應該設置爲false,不然列表刷新時會閃一下】
                .skipMemoryCache(false)
                //緩存策略,硬盤緩存-僅僅緩存最終的圖像,即下降分辨率後的(或者是轉換後的)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                //設置圖片加載的優先級
                .priority(Priority.HIGH)
                .into(mImgBase);

 (1)佈局文件

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#f4f4f4">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="10dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Glide的基礎使用:"/>
        <!-- 圖片使用src和android:scaleType="centerCrop"、android:adjustViewBounds="true",能夠實現寬高等邊 -->
        <ImageView
            android:id="@+id/img_base"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"
            android:contentDescription="@string/app_name"
            android:scaleType="fitCenter"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Glide的從新改變圖片大小(使用override):"/>
        <!-- 圖片使用src和android:scaleType="centerCrop"、android:adjustViewBounds="true",能夠實現寬高等邊 -->
        <ImageView android:id="@+id/img_override" android:layout_width="wrap_content" android:layout_height="wrap_content" android:adjustViewBounds="true" android:contentDescription="@string/app_name" android:scaleType="fitCenter"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Glide的圓形效果(使用RequestOptions#circleCrop())"/>
        <!-- 圖片使用src和android:scaleType="centerCrop"、android:adjustViewBounds="true",能夠實現寬高等邊 -->
        <ImageView android:id="@+id/img_circleCrop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:adjustViewBounds="true" android:contentDescription="@string/app_name" android:scaleType="fitCenter"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Glide的圓角效果(使用RoundedCornersTransformation)"/>
        <!-- 圖片使用src和android:scaleType="centerCrop"、android:adjustViewBounds="true",能夠實現寬高等邊 -->
        <ImageView android:id="@+id/img_round" android:layout_width="wrap_content" android:layout_height="wrap_content" android:adjustViewBounds="true" android:contentDescription="@string/app_name" android:scaleType="fitCenter"/>

    </LinearLayout>

</ScrollView>

 (2)代碼

package com.why.project.glidenewdemo;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import android.widget.ImageView;

import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.myapp.GlideApp;
import com.glide.RoundedCornersTransformation;

import static com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade;

public class MainActivity extends AppCompatActivity {

    private Context mContext;

    private ImageView mImgBase;
    private ImageView mImgOverride;
    private ImageView mImgCircleCrop;
    private ImageView mImgRound;

    private String imgUrl = "https://pic.cnblogs.com/avatar/93830/20170607145247.png";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mContext = this;

        initViews();
        initDatas();
    }

    private void initViews() {
        mImgBase = findViewById(R.id.img_base);
        mImgOverride = findViewById(R.id.img_override);
        mImgCircleCrop = findViewById(R.id.img_circleCrop);
        mImgRound = findViewById(R.id.img_round);
    }

    private void initDatas() {

        glideBase();
        glideOverride();
        glideCircleCrop();
        glideRound();
    }

    //Glide的基礎使用
    private void glideBase() {
        GlideApp.with(mContext) .load(imgUrl) //設置等待時的圖片
 .placeholder(R.drawable.img_loading) //設置加載失敗後的圖片顯示
 .error(R.drawable.img_error) .fitCenter() //默認淡入淡出動畫
 .transition(withCrossFade()) //緩存策略,跳過內存緩存【此處應該設置爲false,不然列表刷新時會閃一下】
                .skipMemoryCache(false) //緩存策略,硬盤緩存-僅僅緩存最終的圖像,即下降分辨率後的(或者是轉換後的)
 .diskCacheStrategy(DiskCacheStrategy.ALL) //設置圖片加載的優先級
 .priority(Priority.HIGH) .into(mImgBase);
    }

    //Glide從新改變圖片大小
    private void glideOverride() {
        setColumnNumber(mContext,3);//計算寬度和高度值(1:1.5或者1:1)
        GlideApp.with(mContext)
                .load(imgUrl)
                //設置等待時的圖片
                .placeholder(R.drawable.img_loading)
                //設置加載失敗後的圖片顯示
                .error(R.drawable.img_error)
                .centerCrop()
                .override(imageWidthSize,imageHeightSize) //默認淡入淡出動畫
                .transition(withCrossFade())
                //緩存策略,跳過內存緩存【此處應該設置爲false,不然列表刷新時會閃一下】
                .skipMemoryCache(false)
                //緩存策略,硬盤緩存-僅僅緩存最終的圖像,即下降分辨率後的(或者是轉換後的)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                //設置圖片加載的優先級
                .priority(Priority.HIGH)
                .into(mImgOverride);
    }

    //用於計算圖片的寬高值
    private int imageWidthSize;
    private int imageHeightSize;

    private void setColumnNumber(Context context, int columnNumber) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(metrics);
        int widthPixels = metrics.widthPixels;
        imageWidthSize = widthPixels / columnNumber;
        imageHeightSize = (int)(imageWidthSize * 1.5);//長方形樣式,二選一
        //imageHeightSize = imageWidthSize;//正方形樣式,二選一
    }

    //Glide的圓形效果
    private void glideCircleCrop() {

        GlideApp.with(mContext)
                .load(imgUrl)
                //設置等待時的圖片【這個時候須要註釋,不然這個會做爲背景圖】 //.placeholder(R.drawable.img_loading) //設置加載失敗後的圖片顯示
                .error(R.drawable.img_error)
                .centerCrop()
                .override(imageWidthSize,imageHeightSize)
                //默認淡入淡出動畫
                .transition(withCrossFade())
                //緩存策略,跳過內存緩存【此處應該設置爲false,不然列表刷新時會閃一下】
                .skipMemoryCache(false)
                //緩存策略,硬盤緩存-僅僅緩存最終的圖像,即下降分辨率後的(或者是轉換後的)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                //設置圖片加載的優先級
                .priority(Priority.HIGH)
                //圓形
 .circleCrop()
                .into(mImgCircleCrop);
    }

    //Glide的圓角效果
    private void glideRound() {
        GlideApp.with(mContext)
                .load(imgUrl)
                //設置等待時的圖片【這個時候須要註釋,不然這個會做爲背景圖】 //.placeholder(R.drawable.img_loading) //設置加載失敗後的圖片顯示
                .error(R.drawable.img_error)
                .centerCrop()
                .override(imageWidthSize,imageHeightSize)
                //默認淡入淡出動畫
                .transition(withCrossFade())
                //緩存策略,跳過內存緩存【此處應該設置爲false,不然列表刷新時會閃一下】
                .skipMemoryCache(false)
                //緩存策略,硬盤緩存-僅僅緩存最終的圖像,即下降分辨率後的(或者是轉換後的)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                //設置圖片加載的優先級
                .priority(Priority.HIGH)
                .transform(new RoundedCornersTransformation(dip2px(mContext,10),0))
                .into(mImgRound);
    }

    /**
     * dp轉px
     * 16dp - 48px
     * 17dp - 51px*/
    public static int dip2px(Context context, float dpValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int)((dpValue * scale) + 0.5f);
    }
}

混淆配置

#glide -keep public class * implements com.bumptech.glide.module.GlideModule -keep public class * extends com.bumptech.glide.module.AppGlideModule -keep public enum com.bumptech.glide.load.ImageHeaderParser$** { **[] $VALUES; public *; } #若是你的 target API 低於 Android API 27,請添加: #-dontwarn com.bumptech.glide.load.resource.bitmap.VideoDecoder #VideoDecoder 使用 API 27 的一些接口,這可能致使 proguard 發出警告,儘管這些 API 在舊版 Android 設備上根本不會被調用。 #若是你使用 DexGuard 你可能還須要添加: # for DexGuard only #-keepresourcexmlelements manifest/application/meta-data@value=GlideModule

官方指南資料

參考資料

Android Glide 4.0+使用

下載和設置

Generated API

從v3遷移到v4

Glide、Picasso、Fresco進階 - 圖像轉換

項目demo下載地址

https://github.com/haiyuKing/GlideNewDemo

相關文章
相關標籤/搜索