Glide加载圆形图片

  • Post author:
  • Post category:其他


Glide加载圆形图片

glide已经在项目中用了一段时间了,算是一个很强大的框架了,最近有个需求,需要加载一张圆形图片,而且图片需要一个边框,网上一大推加载圆形图片的资料,基本都是一样的,但是没有加载边框的!我在原先代码的基础上加了几行,实现了能够加载边框的需求,代码如下:

/**
 * glide加载圆形图片的实现
 */
public class GlideCircleTransform extends BitmapTransformation {

    private int mBorderColor;
    private int mBorderWidth;

    public GlideCircleTransform(Context context) {
        super(context);
    }

    public GlideCircleTransform(Context context, int bordColor, int bordWidth) {
        super(context);
        this.mBorderColor = bordColor;
        this.mBorderWidth = bordWidth;
    }

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

        if (mBorderWidth > 0){
            Paint mBorderPaint = new Paint();
            mBorderPaint.setStyle(Paint.Style.STROKE);
            mBorderPaint.setAntiAlias(true);
            mBorderPaint.setColor(mBorderColor);
            mBorderPaint.setStrokeWidth(mBorderWidth);

            int mBorderRadius = (size - mBorderWidth) / 2;
            canvas.drawCircle(r, r, mBorderRadius, mBorderPaint);
        }
        return bitmap;
    }

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

如果不知道怎么使用,请跳过此文章!!!



版权声明:本文为u013555324原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。