`
ch_kexin
  • 浏览: 877375 次
  • 性别: Icon_minigender_2
  • 来自: 青岛
社区版块
存档分类
最新评论

Android Glide自定义圆角处理

阅读更多

 平时我们开发中会遇到UI出的带圆角的图片,平时做的图片缓存加载框架基本都是 Glide, 那么我们就在Glide上来说一说实现方法。

      Glide是谷歌为我们推荐的一个图片加载库。为什么要选择使用Glide呢?

1、代码有人维护,不至于出现问题,项目组都搞不定的时候问题无法解决。(ImageLoader已没人维护了)

2、代码简洁,可读性很好。(Fresco是一个非常优秀的库,但是配置稍显麻烦,同时代码风格读起来有些生疏)

3、功能强大(400多k的包,包含很多功能,例如:像加载Gif图片就是Picasso做不到的)

        第一步 先是添加依赖:

     //图片

    implementation 'com.github.bumptech.glide:glide:4.5.0'

   (切记一定要申请权限  往往最简单的问题 总是会疏忽)

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<uses-permission android:name="android.permission.INTERNET" />

    然后我们重写一个   (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 RequestOptions属性

* Created by ${ShinnyYang} on 2019/4/11.

*/


public class RequestOptionsStrategy extends RequestOptions {
    @SuppressLint("CheckResult")
    public RequestOptionsStrategy() {
        this.error(R.drawable.error_photo).placeholder(R.drawable.error_photo);
    }
    @SuppressLint("CheckResult")
    public RequestOptionsStrategy(@DrawableRes int errorId,@DrawableRes int placeholderId) {
        this.error(errorId).placeholder(placeholderId);
    }
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics