Glide-图片预处理(圆角,高斯模糊等)

来源:互联网 发布:mac优化 编辑:程序博客网 时间:2024/04/30 06:32

前言:

之前已经讲解过如何简单的显示图片,但是有时候项目中会有很多特殊的需求,比如说圆角处理,圆形图片,高斯模糊等,Glide提供了方法可以很好的进行处理,接下来我们就介绍一下

Glide 系列目录

  • 1.Glide-入门教程
  • 2.Glide-占位图以及加载动画
  • 3.Glide-加载本地图片
  • 4.Glide-加载Gif
  • 5.Glide-绑定生命周期
  • 6.Glide-内存缓存与磁盘缓存
  • 7.Glide-通过Modules定制Glide
  • 8.Glide-自定义缓存
  • 9.Glide-图片的压缩
  • 10.Glide-图片预处理(圆角,高斯模糊等)
  • 11.Glide-图片的剪裁(ScaleType)
  • 12.Glide-源码详解

1.创建一个类继承BitmapTransformation

需要实现两个方法,其中transform方法里面能拿到bitmap对象,这里就是对图片做处理的地方

public  class CornersTransform extends BitmapTransformation {        @Override        protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {            //TODO        }        @Override        public String getId() {           //TODO        }}

2.使用

通过调用transform方法就能展示处理后的图片

Glide.with(this).load(url).transform(new CornersTransform()).into(iv1);

3.举例(圆角处理)


3.1 自定义Transformation

public  class CornersTransform extends BitmapTransformation {    private float radius;    public CornersTransform(Context context) {        super(context);        radius = 10;    }    public CornersTransform(Context context, float radius) {        super(context);        this.radius = radius;    }    @Override    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {        return cornersCrop(pool, toTransform);    }    private Bitmap cornersCrop(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;    }    @Override    public String getId() {        return getClass().getName();    }}

3.2 使用

Glide.with(this).load(url).transform(new CornersTransform(this,50)).into(iv1);

效果如下:

4.使用多个transform

transform方法是不支持多次调用的,如果你调用了两次,那么第二次的会覆盖了第一次的效果

但是他有一个重载的方法可以传入多个对象,这样传入的变形器都能够生效

Glide.with(this).load(url).transform(new CircleTransform(this),new CornersTransform(this,50)).into(iv1);

5.三方库

如果你觉得自己自定义transform比较困难,或者你想学习别人的图片处理方法,可以在试一试github上的这个三方库

Glide Transformations

https://github.com/wasabeef/glide-transformations

效果(支持圆角,高斯模糊等)

热门文章

  • Glide-图片的压缩
  • Glide-内存缓存与磁盘缓存
  • Glide-自定义缓存
  • Glide-入门教程
  • Okhttputils终极封装
  • FaceBook推出的调试神器
  • Android代码优化工具
3 0
原创粉丝点击