android利用glide显示圆角图片

直接上代码:

Glide.with(MyApplication.getMyApplicationContext())
                .load(item.getImage_src())
                .transform(new CenterCrop(MyApplication.getMyApplicationContext()), new GlideRoundTransform(MyApplication.getMyApplicationContext(),4))
                .error(R.mipmap.deault_home3)
                .into(itemImge);
//关键代码
 .transform(new CenterCrop(MyApplication.getMyApplicationContext()), new GlideRoundTransform(MyApplication.getMyApplicationContext(),4))

GlideRoundTransform类,直接复制就可以


/**
 * Created by fengjie on 2016/12/27.
 * 将图片转化为圆角
 * 构造中第二个参数定义半径
 */
public class GlideRoundTransform extends BitmapTransformation {

    private static float radius = 0f;

    public GlideRoundTransform(Context context) {
        this(context, 4);
    }

    public GlideRoundTransform(Context context, int dp) {
        super(context);
        radius = Resources.getSystem().getDisplayMetrics().density * dp;
    }

    @Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        return roundCrop(pool, toTransform);
    }

    private static 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;
    }

    @Override public String getId() {
        return getClass().getName() + Math.round(radius);
    }
}

注意:这样设置圆角的话,xml文件中不要设置centerCrop属性,否则代码是不起作用的,所以要在代码中设置这个属性,上面已经有了。

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