Resize image to full width and variable height with Picasso

前端 未结 12 1552
野趣味
野趣味 2020-11-29 17:10

I have a listView with an adapter that contains ImageView of variable size (width and height). I need resize the pictures load with Picasso to the max width of

12条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 17:53

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

        Transformation transformation = new Transformation() {
    
            @Override
            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
                    source.recycle();
                }
                return result;
            }
    
            @Override
            public String key() {
                return "transformation" + " desiredWidth";
            }
        };
    
        mMessage_pic_url = message_pic_url;
    
        Picasso.with(this.context)
            .load(message_pic_url)
            .error(android.R.drawable.stat_notify_error)
            .transform(transformation)
            .into(holder.message_picture, new Callback() {
                @Override
                public void onSuccess() {
                    holder.progressBar_picture.setVisibility(View.GONE);
                }
    
                @Override
                public void onError() {
                    Log.e(LOGTAG, "error");
                    holder.progressBar_picture.setVisibility(View.GONE);
                }
        });
    

    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.

提交回复
热议问题