?平時(shí)我們開發(fā)中會(huì)遇到UI出的帶圓角的圖片心傀,平時(shí)做的圖片緩存加載框架基本都是 Glide猜扮,?那么我們就在Glide上來說一說實(shí)現(xiàn)方法。
? ? ? Glide是谷歌為我們推薦的一個(gè)圖片加載庫夜焦。為什么要選擇使用Glide呢捞稿?
1、代碼有人維護(hù)荞胡,不至于出現(xiàn)問題妈踊,項(xiàng)目組都搞不定的時(shí)候問題無法解決。(ImageLoader已沒人維護(hù)了)
2硝训、代碼簡潔响委,可讀性很好。(Fresco是一個(gè)非常優(yōu)秀的庫窖梁,但是配置稍顯麻煩赘风,同時(shí)代碼風(fēng)格讀起來有些生疏)
3、功能強(qiáng)大(400多k的包纵刘,包含很多功能邀窃,例如:像加載Gif圖片就是Picasso做不到的)
? ? ? ? 第一步?先是添加依賴:
? ? ?//圖片
? ? implementation 'com.github.bumptech.glide:glide:4.5.0'
? ?(切記一定要申請權(quán)限? 往往最簡單的問題?總是會(huì)疏忽)
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
? ? 然后我們重寫一個(gè)? ?(GlideRoundTransform)
/**
* Created by ShinnyYang on 2018/6/6.
* 自定義glide的圓角處理部分
*/
public class GlideRoundTransform extends BitmapTransformation {
? ? private float radius = 0f;
? ? public GlideRoundTransform(Context context) {
? ? ? ? this(context, 4);
? ? }
? ? public GlideRoundTransform(Context context, int dp) {
? ? ? ? this.radius = Resources.getSystem().getDisplayMetrics().density * dp;
? ? }
? ? @Override
? ? protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
? ? ? ? Bitmap bitmap = TransformationUtils.centerCrop(pool, toTransform, outWidth, outHeight);
? ? ? ? return roundCrop(pool, bitmap);
? ? }
? ? private Bitmap roundCrop(BitmapPool pool, Bitmap source) {
? ? ? ? if (source == null) return null;
? ? ? ? Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
? ? ? ? if (result == null) {
? ? ? ? ? ? result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
? ? ? ? }
? ? ? ? Canvas canvas = new Canvas(result);
? ? ? ? Paint paint = new Paint();
? ? ? ? paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
? ? ? ? paint.setAntiAlias(true);
? ? ? ? RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
? ? ? ? canvas.drawRoundRect(rectF, radius, radius, paint);
? ? ? ? return result;
? ? }
? ? public String getId() {
? ? ? ? return getClass().getName() + Math.round(radius);
? ? }
? ? @Override
? ? public void updateDiskCacheKey(MessageDigest messageDigest) {
? ? }
? 代碼中使用
Glide.with(mContext)
? ? ? ? .load(t.getBody().getGoods().getPic_url())
? ? ? ? .apply(new RequestOptionsStrategy()
? ? ? ? ? ? ? ? .transform(new GlideRoundTransform(mContext, 5)))
? ? ? ? .into(ivHeadPic);
附加?
/**
* glide RequestOptions屬性
* Created by ${ShinnyYang} on 2019/4/11.
*/
public class RequestOptionsStrategy extends RequestOptions {
? ? @SuppressLint("CheckResult")
? ? public RequestOptionsStrategy() {
? ? ? ? this.error(R.color.greed)
? ? ? ? ? ? ? ? .placeholder(R.color.greed);
? ? }
}