Picasso crop to a view

2019-01-20 09:39发布

问题:

How would I use picasso to crop an image to an imageview?

Default seems to scale it down so the whole thing shows fit seems to stretch it. centercrop by itself breaks. fit centercrop seems to be the same as just fit

Thanks

回答1:

Try using centerCrop()

Picasso.with(mContext)
.load(url)
.centerCrop()
.resize(yourImageView.getMeasuredWidth(),yourImageView.getMeasuredHeight())
.error(R.drawable.error)
.placeholder(R.drawable.blank_img)
.into(yourImageView);

You have to add addOnPreDrawListener listener otherwise you will get 0 for width and height when the imageview is not drawn. Go here for details on how to use addOnPreDrawListener.



回答2:

You must call resize before calling centerCrop or centerInside() methods otherwise Picasso complains about target width/height being 0.

public class MainActivity extends Activity {
ImageView imageView;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    imageView = (ImageView) findViewById(R.id.imageView);
}

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    if (hasFocus) {
        Picasso.with(this)
                .load("http://i.imgur.com/removed.png")
                .resize(imageView.getMeasuredWidth(), imageView.getMeasuredHeight())
                .centerCrop() // or centerInside()
                .into(imageView);
    }
    super.onWindowFocusChanged(hasFocus);
}
}

And here's the imageView defined within layout:

 <ImageView
    android:layout_width="160dp"
    android:layout_height="160dp"
    android:id="@+id/imageView"
    />


回答3:

CenterCrop() is a cropping technique that scales the image so that it fills the requested bounds of the ImageView and then crops the extra. The ImageView will be filled completely, but the entire image might not be displayed.

Picasso  
.with(context)
.load(UsageExampleListViewAdapter.eatFoodyImages[0])
.resize(600, 200) // resizes the image to these dimensions (in pixel)
.centerCrop() 
.into(imageViewResizeCenterCrop);

CenterInside() is a cropping technique that scales the image so that both dimensions are equal to or less than the requested bounds of the ImageView. The image will be displayed completely, but might not fill the entire ImageView.

Picasso  
.with(context)
.load(UsageExampleListViewAdapter.eatFoodyImages[0])
.resize(600, 200)
.centerInside() 
.into(imageViewResizeCenterInside);

The discussed options should cover your needs for functionality regarding image resizing and scaling. There is one last helper functionality of Picasso, which can be very useful: fit().

Picasso  
.with(context)
.load(UsageExampleListViewAdapter.eatFoodyImages[0])
.fit()
// call .centerInside() or .centerCrop() to avoid a stretched image
.into(imageViewFit);