Android shared elements with Picasso

2020-07-16 01:16发布

问题:

I'm trying to make an image transit from a list in one activity to a detail activity.

In the detail activity the image is bigger than in the list and I'm using Picasso to retrieve the image from the server.

The problem is that the first time I launch the detail activity, the image transit well but is not resized nor centered. When I go back, the image is instantly resized, and if I come back to the same detail activity, it works as expected.

The detail activity call method:

public static void launch(Activity activity, View transitionView,
                          StoreProduct storeProduct) {

    ActivityOptionsCompat options =
            ActivityOptionsCompat.makeSceneTransitionAnimation(
                    activity, transitionView, activity.getString(R.string
                            .transition_product_image));
    Intent intent = new Intent(activity, ProductDetailActivity.class);
    intent.putExtra(PARAM_STORE_PRODUCT, storeProduct);
    ActivityCompat.startActivity(activity, intent, options.toBundle());
}

The Picasso image loading in the detail activity:

Picasso.with(this).load(product.imageUrl).fit().centerInside()

Thanks for your help

回答1:

try to use transformation based on your need.

Transformation transformation = new Transformation() {

        @Override
        public Bitmap transform(Bitmap source) {
            int targetWidth = context.getResources().getDisplayMetrics().widthPixels - lessWidth;
            if (source.getWidth() > targetWidth) {
                double aspectRatio = (double) source.getHeight()
                        / (double) source.getWidth();
                int targetHeight = (int) (targetWidth * aspectRatio);
                Bitmap result = Bitmap.createScaledBitmap(source,
                        targetWidth, targetHeight, false);
                if (result != source) {
                    source.recycle();
                }
                return result;
            }
            return source;
        }

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

this object can be used as below:

Picasso.with(context).load(strImageUrl).transform(transformation)
            .into(imageView, new com.squareup.picasso.Callback() {

                @Override
                public void onSuccess() {
                    Log.d("Picasso", "ImageLoadSuccess");                       
                }

                @Override
                public void onError() {
                    Log.d("PicassoHelper", "ImageLoadError");
                    if (imageView!=null&&defaultBitmap!=null) {
                        imageView.setImageBitmap(defaultBitmap);
                    }                       
                }
            });

hope this will help in your problem.