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);
}

并且我想在宽度为 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);

结果不应该一样吗?因为显然一个比另一个宽得多。

enter image description here

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/

相关文章:

android - android 是否可以通过 NDK 开发 eap-sim 连接?

android - 如何在android studio中添加 picasso 库

android - 如何在 ImageView 上获取图像的 ID?

android - 在 picasso 中使用回调获取图像?

java - 重新打开 Android 应用程序时 SQLite 表为空

android - 将文件保存在闪存中

android - Card.io 可以与 Stripe 集成,还是与 PayPal 严格预集成?

android - 如何在一个应用程序中设置两个不同的启动器名称和图标 (android)

Android - 让 ImageView 适合 ListView

java - 如何使用 Picasso 加载 Google map 静态 map ?