Glide4加载图片显示圆角和显示头像圆形图片

用于记录工具

 /**
     * 加载圆形图片
     * @param context
     * @param view
     * @param url
     */
    public static void setCirclePicture(Context context, ImageView view, String url) {
        GlideApp.with(context)
                .load(url)
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                .error(R.mipmap.head_deficon)
                .placeholder(R.mipmap.head_deficon)
                .transform(new CircleCrop())
                .into(view);
    }
 /**
     * 加载圆角图片
     *
     * @param context 上下文
     * @param view    图片控件
     * @param url     网络图片地址
     * @param radius  圆角度数
     * @param errorid 错误图片
     */

    public static void setPicture(Context context, ImageView view, String url, int radius,
                                   @DrawableRes int errorid) {
        if (view == null) {
            return;
        }
        RequestOptions options = bitmapTransform(new CenterCropRoundCornerTransform(radius));
        GlideApp.with(context)
                .load(url)
                .apply(options)
                .placeholder(R.drawable.loading)
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                .error(errorid)
                .into(view);
    }

关键类;

public class CenterCropRoundCornerTransform extends CenterCrop {
    private static float radius = 0f;

    public CenterCropRoundCornerTransform(int px) {
        this.radius = px;
    }

    @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 static Bitmap roundCrop(BitmapPool pool, Bitmap source) {
        if (source == null) return null;

        Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_4444);
        if (result == null) {
            result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_4444);
        }

        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) {

    }
}

 

你可能感兴趣的:(工具)