我正在使用以下代码将 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);
}
并且我想在宽度为 160dp
的 ImageView 中显示图像。
我首先尝试仅使用 android 框架来显示图像,然后我也尝试了 Picasso
库。
让我觉得有趣的是,我得到了视觉上不同的结果,但我不知道如何解释它。所以我做了一个演示应用程序来测试它,这是我屏幕上的代码和结果:
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 的 resize
没有指定缩放类型则不会。所以你的两种方法并没有做完全相同的事情。
要获得相同的结果,请将 Picasso 调用更改为:
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"/>
关于android - 使用 Picasso 加载相同图像时宽度不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39395387/