我正在使用Picasso库在ViewPager中加载和显示图像。正在加载的图像具有高分辨率,我想为它们添加一个非采样大小。但是,我不知道应该如何或在何处添加此采样大小属性。我的ViewPagerAdapter.java类有以下内容。
@Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView iv_page_image;
inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.viewpager_item, container,false);
iv_page_image = (ImageView) itemView.findViewById(R.id.iv_page_image);
String path = pageList.get(position).getPageImage();
path = path.replaceAll(" ", "%20");
if (path != null && !(path.equalsIgnoreCase(""))) {
Picasso.with(mContext).load(path)
.placeholder(R.drawable.placeholder_empty)
.into(iv_page_image, new Callback() {
@Override
public void onSuccess() {
}
@Override
public void onError() {
}
});
}
((ViewPager) container).addView(itemView);
return itemView;
}
我想在图片中添加如下内容
private static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
答案 0 :(得分:7)
只需将.fit()
添加到您对Picasso的调用中,它就会自动计算解码图片时使用的相应inSampleSize
。
您可能还想使用.centerInside()
或.centerCrop()
来确保自动调整大小时图像的宽高比不会改变。