165

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)?

Cassie
  • 4,722
  • 3
  • 20
  • 34
David Rabinowitz
  • 28,033
  • 14
  • 88
  • 124

2 Answers2

497

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.
Jake Wharton
  • 72,540
  • 21
  • 218
  • 227
  • 5
    What should be the height of the imageView? I don't want a fixed height for my imageView. It should change according to the height of the image. – Chetna Jan 07 '17 at 12:41
  • 4
    `.fit().centerInside()` worked for me where just using `.centerInside()` was crashing with `Center inside requires calling resize with positive width and height.` error message. – Rock Lee May 10 '17 at 21:17
  • @Rock Lee, you need to resize it : ' .load(url) .resize(targetWidth, targetHeight) '......... – FRK Oct 01 '17 at 22:15
  • 9
    `.fit().centerCrop()` or `.fit().centerInside()` is not working. Image is not loading in `imageView`. without `.fit()` image is loading fine. I am not using `.resize()` in both cases. – Nishant Bhakta Oct 25 '17 at 07:40
  • how to resize it without cropping it from any side and also maintaining the aspect – Rohit Sharma Nov 22 '18 at 10:54
2

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);
            }
        });
Community
  • 1
  • 1
Umut ADALI
  • 893
  • 1
  • 11
  • 26