Resize image to full width and variable height with Picasso

前端 未结 12 1574
野趣味
野趣味 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:44

    May Accepted Answer is Useful to all but If you are binding Multiple ViewHolder for Multiple Views then you can reduce your code by Creating Class for Transformation and passing ImageView from ViewHolder.

    /**
     * Created by Pratik Butani
     */
    public class ImageTransformation {
    
        public static Transformation getTransformation(final ImageView imageView) {
            return new Transformation() {
    
                @Override
                public Bitmap transform(Bitmap source) {
                    int targetWidth = imageView.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";
                }
            };
        }
    }
    

    Calling from ViewHolder:

    Picasso.with(context).load(baseUrlForImage)
                         .transform(ImageTransformation.getTransformation(holder.ImageView1))
                         .error(R.drawable.ic_place_holder_circle)
                         .placeholder(R.drawable.ic_place_holder_circle)
                         .into(holder.mMainPhotoImageView1);
    

    Hope it will Help you.

提交回复
热议问题