Glide加载圆形和圆角图片+使用记录

前言

因为项目中使用了Glide,同时了为了兼容性,所以在加载圆角和圆形图片的时候,是使用Gilde来实现,而不是通过自定义控件,此文是记录下如果通过Glide加载圆形和圆角图片,以及在使用Glide中常用的一些方法

加载有效果的图片方式

Glide可以通过设置transform或者设置bitmapTransform来实现各种现实效果,本文是通过设置transform来实现的圆角和圆形图片

加载圆角图片

调用代码

Glide.with(activity).load(uri).centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL)  
                .transform(new CornersTransform(activity))
                .placeholder(R.drawable.ic_gf_default_photo)
                .error(R.drawable.ic_gf_default_photo)
                .crossFade()
                .into(imageView);
import android.content.Context;  
import android.graphics.Bitmap;  
import android.graphics.BitmapShader;  
import android.graphics.Canvas;  
import android.graphics.Paint;  
import android.graphics.RectF;

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

/**
 * 圆角效果的Transform
 * Created by Raye on 2016/5/10.
 */
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();
    }
}

加载圆形图片

Glide.with(activity).load(uri).centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL)  
                .transform(new CircleTransform(activity))
                .placeholder(R.drawable.ic_gf_default_photo)
                .error(R.drawable.ic_gf_default_photo)
                .crossFade()
                .into(imageView);
import android.content.Context;  
import android.graphics.Bitmap;  
import android.graphics.BitmapShader;  
import android.graphics.Canvas;  
import android.graphics.Matrix;  
import android.graphics.Paint;

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

/**
 * 圆形的Transformation
 * Created by Raye on 2016/5/3.
 */
public 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  Bitmap circleCrop(BitmapPool pool, Bitmap source) {

        int size = Math.min(source.getWidth(), source.getHeight());

        int width = (source.getWidth() - size) / 2;
        int height = (source.getHeight() - size) / 2;

        Bitmap bitmap = pool.get(size, size, Bitmap.Config.ARGB_8888);
        if (bitmap == null) {
            bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
        }

        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        BitmapShader shader =
                new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
        if (width != 0 || height != 0) {
            // source isn't square, move viewport to center
            Matrix matrix = new Matrix();
            matrix.setTranslate(-width, -height);
            shader.setLocalMatrix(matrix);
        }
        paint.setShader(shader);
        paint.setAntiAlias(true);

        float r = size / 2f;
        canvas.drawCircle(r, r, r, paint);

        return bitmap;
    }

    @Override
    public String getId() {
        return getClass().getName();
    }
}

获取缓存大小

    /**
     * 获取缓存大小
     * @param dir 缓存目录
     * @return 缓存的大小
     */
    private static long calculateSize(File dir) {
        if (dir == null) return 0;
        if (!dir.isDirectory()) return dir.length();
        long result = 0;
        File[] children = dir.listFiles();
        if (children != null)
            for (File child : children)
                result += calculateSize(child);
        return result;
    }
long totalSize = calculateSize(new File(getCacheDir(), DiskCache.Factory.DEFAULT_DISK_CACHE_DIR));  

注意:calculateSize方法必须要在非UI线程调用,因为计算缓存默认是耗时操作,如果在UI线程调用,会抛异常,计算出来的结果可以通过

android.text.format.Formatter.formatFileSize(getContext(), totalSize );  

进行格式化

获取指定URL的缓存地址

    /**
     * 获取缓存的地址
     * Create by Raye on 2016年8月5日11:26:15
     * @param url 图片url
     * @param context 上下文
     * @return 图片路径
     */
    public static String getImgPath(String url,Context context){
        FutureTarget<File> future = Glide.with(context)
                .load(url)
                .downloadOnly(500, 500);
        try {
            File cacheFile = future.get();
            return cacheFile.getAbsolutePath();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }

注意:这个方法也必须要在非UI线程调用,否则会抛异常,当然我怀疑这个如果没有缓存,是会从网络下载下来,再缓存,最后返回的

清理缓存

Glide.get(context).clearDiskCache();  

结尾

以上就是我在使用Glide中的一些笔记,记录下来方便下次使用,当然如果你看到了你想要的东西就更好了,最近天天加班忙成狗,新版APP上线了,终于得空写下博客了。最后欢迎大家吐槽交流(QQ群:123965382)

标签:Android, Glide
下一篇:   Android 一些面试问题收集
上一篇:   设计模式之单例模式

Copyright © 2017 Raye Blog

如果我的文章对你有帮助,或许可以打赏一下呀!

支付宝
微信