How to round an image with Glide library?

前端 未结 22 1860
悲哀的现实
悲哀的现实 2020-11-28 00:46

So, anybody know how to display an image with rounded corners with Glide? I am loading an image with Glide, but I don\'t know how to pass rounded params to this library.

22条回答
  •  囚心锁ツ
    2020-11-28 01:01

    Check this post, glide vs picasso...
    Edit: the linked post doesn't call out an important difference in the libraries. Glide does the recycling automatically. See TWiStErRob's comment for more.

    Glide.with(this).load(URL).transform(new CircleTransform(context)).into(imageView);
    
    public static class CircleTransform extends BitmapTransformation {
        public CircleTransform(Context context) {
            super(context);
        }
    
        @Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
            return circleCrop(pool, toTransform);
        }
    
        private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
            if (source == null) return null;
    
            int size = Math.min(source.getWidth(), source.getHeight());
            int x = (source.getWidth() - size) / 2;
            int y = (source.getHeight() - size) / 2;
    
            // TODO this could be acquired from the pool too
            Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
    
            Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
            if (result == null) {
                result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
            }
    
            Canvas canvas = new Canvas(result);
            Paint paint = new Paint();
            paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
            paint.setAntiAlias(true);
            float r = size / 2f;
            canvas.drawCircle(r, r, r, paint);
            return result;
        }
    
        @Override public String getId() {
            return getClass().getName();
        }
    } 
    

提交回复
热议问题