美文网首页
android Glide3.7 圆角图片

android Glide3.7 圆角图片

作者: 读书人heart | 来源:发表于2019-07-19 20:04 被阅读0次

    导入

    implementation 'com.github.bumptech.glide:glide:3.7.0'
    

    样式类

    import android.content.Context;
    import android.content.res.Resources;
    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;
    
    public class GlideRoundTransform extends BitmapTransformation {
        private static float radius = 0f;
    
        /**
         * 构造函数 默认圆角半径 4dp
         *
         * @param context Context
         */
        public GlideRoundTransform(Context context) {
            this(context, 4);
        }
        /**
         * 构造函数
         *
         * @param context Context
         * @param dp 圆角半径
         */
        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);
        }
    
    }
    
    

    使用

    Glide.with(context)
                        .load(url)
                        .transform(new CenterCrop(context),new GlideRoundTransform(context))
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .placeholder(R.mipmap.ic_launcher)
                        .dontAnimate()
                        .crossFade()
                        .into(ImageView);
    

    相关文章

      网友评论

          本文标题:android Glide3.7 圆角图片

          本文链接:https://www.haomeiwen.com/subject/hamnkctx.html