Resize image to full width and variable height with Picasso

前端 未结 12 1600
野趣味
野趣味 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:54

    As of Picasso 2.4.0, this operation is now directly supported. Simply add a .resize() request with one of the dimensions as 0. For example, to have a variable width, your call would become:

    Picasso.with(this.context)
           .load(message_pic_url)
           .placeholder(R.drawable.profile_wall_picture)
           .resize(0, holder.message_picture.getHeight()),
           .into(holder.message_picture);
    

    Note that this call uses .getHeight() and therefore assumes the message_picture has already been measured. If that isn't the case, such as when you have inflated a new view in a ListAdapter, you can delay this call until after measurement by adding an OnGlobalLayoutListener to the view:

    holder.message_picture.getViewTreeObserver()
          .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                // Wait until layout to call Picasso
                @Override
                public void onGlobalLayout() {
                    // Ensure we call this only once
                    imageView.getViewTreeObserver()
                             .removeOnGlobalLayoutListener(this);
    
    
                    Picasso.with(this.context)
                           .load(message_pic_url)
                           .placeholder(R.drawable.profile_wall_picture)
                           .resize(0, holder.message_picture.getHeight())
                           .into(holder.message_picture);
                }
            });
    

提交回复
热议问题