Resize image to full width and fixed height with Picasso

JavaAndroidImageviewImage ResizingPicasso

Java Problem Overview


I have a vertical LinearLayout where one of the items is an ImageView loaded using Picasso. I need to rise the image's width to the full device width, and to display the center part of the image cropped by a fixed height (150dp). I currently have the following code:

Picasso.with(getActivity()) 
    .load(imageUrl) 
    .placeholder(R.drawable.placeholder) 
    .error(R.drawable.error) 
    .resize(screenWidth, imageHeight)
    .centerInside() 
    .into(imageView);

Which values should I put into screenWidth and imageHeight (=150dp)?

Java Solutions


Solution 1 - Java

You are looking for:

.fit().centerCrop()

What these mean:

  • fit - wait until the ImageView has been measured and resize the image to exactly match its size.
  • centerCrop - scale the image honoring the aspect ratio until it fills the size. Crop either the top and bottom or left and right so it matches the size exactly.

Solution 2 - Java

In some case the fit() is useless. Before you must wait for the width and height measurement to end. So you can use globallayoutlistener. for example;

imageView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            public void onGlobalLayout() {
                Picasso.with(getActivity())
                        .load(imageUrl)
                        .placeholder(R.drawable.placeholder)
                        .error(R.drawable.error)
                        .resize(screenWidth, imageHeight)
                        .fit
                        .centerInside()
                        .into(imageView);
                imageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid RabinowitzView Question on Stackoverflow
Solution 1 - JavaJake WhartonView Answer on Stackoverflow
Solution 2 - JavaUmut ADALIView Answer on Stackoverflow