Android 与毕加索加载相同图像时的不同宽度
我使用以下代码将dp转换为像素:Android 与毕加索加载相同图像时的不同宽度,android,picasso,Android,Picasso,我使用以下代码将dp转换为像素: public static int convertDpToPixel(float dp){ DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics(); float px = dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT); return Math.round(px); } 我想在
public static int convertDpToPixel(float dp){
DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
float px = dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
return Math.round(px);
}
我想在ImageView中显示宽度为160dp
的图像
我首先尝试只使用android框架来显示图像,然后我还尝试了Picasso
library
有趣的是,我得到了一个视觉上不同的结果,我不知道如何解释它。因此,我制作了一个演示应用程序来测试它,下面是我屏幕上的代码和结果:
int width = ImageHelper.convertDpToPixel(160);
int height = ImageHelper.convertDpToPixel(100);
ivNative = (ImageView) findViewById(R.id.iv_native);
ivPicasso = (ImageView) findViewById(R.id.iv_picasso);
ivNative.setImageResource(R.drawable.placeholder);
ivNative.getLayoutParams().width = width;
ivNative.getLayoutParams().height = height;
ivNative.requestLayout();
Picasso.with(this)
.load(R.drawable.placeholder)
.resize(width, height)
.into(ivPicasso);
结果不应该是一样的吗?因为很明显,一个比另一个宽得多
XML代码:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="test.checkpicasso.MainActivity">
<ImageView android:id="@+id/iv_native"
android:layout_margin="8dp"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
<ImageView android:id="@+id/iv_picasso" android:layout_below="@+id/iv_native"
android:layout_margin="8dp"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
</RelativeLayout>
默认情况下,
ImageView
将尝试保留内容的纵横比(而不是挤压),而毕加索的调整大小
而不指定缩放类型则不会。所以你的两种方法做的事情并不完全相同
要获得相同的结果,请将毕加索调用更改为:
Picasso.with(this)
.load(R.drawable.placeholder)
.resize(width, height)
.centerInside()
.into(ivPicasso);
或者,将ImageView
xml更改为:
<ImageView android:id="@+id/iv_native"
android:layout_margin="8dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitXY"/>
ImageView默认情况下会尝试保持纵横比,而Picasso resize则不会。因此,这只是比例类型的问题,宽度没有问题?正确-两个图像视图的宽度相同-只是第一个视图中的位图没有拉伸以填充该宽度,以保持纵横比。@KenWolf确实如此!我刚刚试着将“刻度类型”设置为fitXY,它们是一样的!谢谢!!