Using picasso library with a circle image view

前端 未结 5 1481
长发绾君心
长发绾君心 2021-01-04 00:45

I am looking at using the Picasso library to download an image from URL and pass this into circle image view, but since picasso requires that you pass in an actual imageView

5条回答
  •  -上瘾入骨i
    2021-01-04 01:17

    I have created a target class that uses native Android's RoundedBitmapDrawable class to make image round (removes the need to add a circle transform class to code), see solution below:

    public class RoundedImageBitmapTarget implements Target {
    
        private final Context context;
        private final ImageView view;
    
        public RoundedImageBitmapTarget(Context context, ImageView view) {
            this.context = context;
            this.view = view;
        }
    
        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
            setBitmap(bitmap);
        }
    
        @Override
        public void onBitmapFailed(Drawable errorDrawable) {
            setBitmap(((BitmapDrawable) errorDrawable).getBitmap());
        }
    
        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {
            setBitmap(((BitmapDrawable) placeHolderDrawable).getBitmap());
        }
    
        public void setBitmap(Bitmap bitmap) {
            view.setImageDrawable(getRoundBitmap(context, bitmap));
        }
    
        public static RoundedBitmapDrawable getRoundBitmap(Context context, Bitmap bitmap) {
            Resources res = context.getResources();
            RoundedBitmapDrawable round = RoundedBitmapDrawableFactory.create(res, bitmap);
            round.setCircular(true);
            round.setTargetDensity(context.getResources().getDisplayMetrics());
            return round;
        }
    
        public static void load(Context context, ImageView view, String url, int size, @DrawableRes int placeholder) {
            RoundedImageBitmapTarget target;
            Picasso.with(context).load(url)
                    .resize(0, size)
                    .placeholder(placeholder)
                    .error(placeholder)
                    .into(target = new RoundedImageBitmapTarget(context, view));
            view.setTag(target);
        }
    
    }
    

提交回复
热议问题