wendigo wendigo - 2 years ago 799
Android Question

Resize image to full width and variable height with Picasso

I have a listView with an adapter that contains

of variable size (width and height). I need resize the pictures load with Picasso to the max width of layout and a variable height given by the aspect ratio of the picture.

I have checked this question:
Resize image to full width and fixed height with Picasso

works but I haven't found nothing to keep the aspect ratio of the picture.

This code partially works if I fixed the height in the layout of the adapter:


But it generates blank spaces between the pictures of the listView because the pictures may be that not have that height.

Thanks in advance.

Answer Source

Finally I solved it doing a transformation of Picasso, here is the snippet:

    Transformation transformation = new Transformation() {

        public Bitmap transform(Bitmap source) {
            int targetWidth = holder.message_picture.getWidth();

            double aspectRatio = (double) source.getHeight() / (double) source.getWidth();
            int targetHeight = (int) (targetWidth * aspectRatio);
            Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
            if (result != source) {
                // Same bitmap is returned if sizes are the same
            return result;

        public String key() {
            return "transformation" + " desiredWidth";

    mMessage_pic_url = message_pic_url;

        .into(holder.message_picture, new Callback() {
            public void onSuccess() {

            public void onError() {
                Log.e(LOGTAG, "error");

This line is for customize with your desired width:

int targetWidth = holder.message_picture.getWidth();

Additionally this snipped include Callback for loading hide and error drawable built-in Picasso.

If you need more information to debug any error, you MUST implement a custom listener (Picasso builder) beacuse the onError Callback information is "null". You only know that there is an error for UI behavior.

I hope this helps someone to save many hours.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download