Resize image to full width and variable height with Picasso

前端 未结 12 1565
野趣味
野趣味 2020-11-29 17:10

I have a listView with an adapter that contains ImageView of variable size (width and height). I need resize the pictures load with Picasso to the max width of

12条回答
  •  执念已碎
    2020-11-29 17:45

    I've wrote simple helper that take care about adding layout complete listener and call into(imageView) when layout process complete.

    public class PicassoDelegate {
    
    private RequestCreator mRequestCreator;
    
    public PicassoDelegate(ImageView target, RequestCreator requestCreator) {
        if (target.getWidth() > 0 && target.getHeight() > 0) {
            complete(target, requestCreator);
        } else {
            mRequestCreator = requestCreator;
            target.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
                @Override
                public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                    v.removeOnLayoutChangeListener(this);
                    complete((ImageView) v, mRequestCreator);
                }
            });
    
        }
    
    }
    
    private void complete(ImageView target, RequestCreator requestCreator) {
        if (target.getWidth() > 0 && target.getHeight() > 0) {
            requestCreator.resize(target.getWidth(), target.getHeight());
        }
    
        requestCreator.into(target);
    }
    

    }

    So you can easily use it like this for example in fragment's onViewCreated()

    new PicassoDelegate(customerPhoto, Picasso.with(getActivity()).load(user.getPhotoUrl()).centerCrop());
    

提交回复
热议问题