Mes Mes - 2 months ago 29
Android Question

Different width when loading same image with Picasso

I'm using the following code to convert dp to pixels :

public static int convertDpToPixel(float dp){
DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
float px = dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
return Math.round(px);
}


and I want to display an image in an ImageView with width of
160dp
.

I first tried using just the android framework to display the image and then I gave a try also to
Picasso
library.

To my amusement I get a visual different result and I don't know how to explain it. So I made a demo app to test it and here is the code and the result in my screen :

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


Shouldn't the result be the same? Cause obviously one is much wider than the other.

enter image description here

XML code :

<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>

Answer

An ImageView by default will attempt to preserve the aspect ratio of the content (not squash it) whereas Picasso's resize without specifying a scale type will not. So your two methods are not doing exactly the same thing.

To achieve the same result change your Picasso call to:

Picasso.with(this)
    .load(R.drawable.placeholder)
    .resize(width, height) 
    .centerInside()
    .into(ivPicasso);

Alternatively, change your ImageView xml to:

<ImageView android:id="@+id/iv_native"
  android:layout_margin="8dp"
  android:layout_width="wrap_content" 
  android:layout_height="wrap_content" 
  android:scaleType="fitXY"/>
Comments