天天看點

Glide加載圓形圖檔Glide加載圓形圖檔

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) / ;
        int height = (source.getHeight() - size) / ;

        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 !=  || height != ) {
            Matrix matrix = new Matrix();
            matrix.setTranslate(-width, -height);
            shader.setLocalMatrix(matrix);
        }
        paint.setShader(shader);
        paint.setAntiAlias(true);
        float r = size / f;
        canvas.drawCircle(r, r, r, paint);

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

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

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

如果不知道怎麼使用,請跳過此文章!!!