昨天写了Glide转化圆形图片的ImageView,然后就把我坑了好久。。。。。。。
Demo地址:https://github.com/HarryXR/GlideImageView
1.首先导包
compile 'com.github.bumptech.glide:glide:3.6.1'
2.开始实现
查看文档发现实现圆形图片都是重写Glide的BitmapTransformation类
使用方式:
- Glide.with(context).load(url).transform(new CircleTransForm(context)).into(iv);
- public static class CircleTransform extends BitmapTransformation {
- public CircleTransform(Context context) {
- super(context);
- }
- @Override
- protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
- return circleCrop(pool, toTransform);
- }
- private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
- if (source == null) {
- return null;
- }
- int size = Math.min(source.getWidth(), source.getHeight());
- int x = (source.getWidth() - size) / 2;
- int y = (source.getHeight() - size) / 2;
- // TODO this could be acquired from the pool too
- Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
- Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
- if (result == null) {
- result = Bitmap.createBitmap(size, size, 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);
- float r = size / 2f;
- canvas.drawCircle(r, r, r, paint);
- return result;
- }
- @Override
- public String getId() {
- return getClass().getName();
- }
- }
由于我要定制Glide的加载功能,没有使用上诉拼接加载的方式
- builder = (DrawableTypeRequest) Glide.with(context).load(url).dontAnimate();
- builder.transform(new CircleTransForm(context));
- builder.into(this);
坑点来了
DrawableTypeRequest是DrawableRequestBuilder的子类,在我的使用方法中,不能使用
DrawableRequestBuilder来添加transform
必须使用DrawableTypeRequest才能实现圆形图片的转化。