5

I have got this code to crossfade the background of an ImageView:

private void setWithCrossfade(Bitmap bitmap) {
    //create drawable vector
    Drawable backgrounds[] = new Drawable[2];
    //getting first image
    backgrounds[0] = mImageView.getDrawable();
    backgrounds[1] = new BitmapDrawable(mImageView.getResources(), bitmap);

    TransitionDrawable transitionDrawable = new TransitionDrawable(backgrounds);
    transitionDrawable.setCrossFadeEnabled(true);

    mImageView.setAdjustViewBounds(false);
    mImageView.setImageDrawable(transitionDrawable);
    //it is needed to reset scale type
    mImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    //start crossfading
    transitionDrawable.startTransition(250);
}

The ImageView scaleType is set to centerCrop in the XML layout. However, when the crossfade finishes, the new bitmap is set to fitXY. In other thread they say it can be solved by resetting the scaleType, but it is not working either. Resizing the bitmap is not a proper solution in terms of memory. Is there any workaround to implement this? Thank you very much.

P.S.: Please, do not suggest crossfading 2 ImageViews, or using a ViewSwitcher thanks.

Mattia Maestrini
  • 32,270
  • 15
  • 87
  • 94
Quark
  • 402
  • 4
  • 15

1 Answers1

3

I had the same problem. The problem is that a TransitionDrawable needs two drawables of the same size. If it is not the same size it stretches to the size of the first Image. Picasso already handles this. So I took the PicassoDrawable from Picasso and first set the placeholder and then the bitmap.

PicassoDrawable.setPlaceholder(imageView, placeholderDrawable);
PicassoDrawable.setBitmap(imageView, context, bitmap);

You may need to set the class and those methods to public. Also I removed some methods only relevant for Picasso. Now it should fade correctly with different image sizes.

Kevin van Mierlo
  • 9,554
  • 5
  • 44
  • 76
  • This actually works; however, the current placeholder shrinks for a sec before the transition run. Therefore, this only reverses the problem not solving it. – Mohamed Salah Jan 19 '20 at 05:47
  • 1
    @MohamedSalah If the aspect ratio's are different then it would indeed change in size. But this does fix the issue that the second image is the wrong aspect ratio. It actually changes the intrinsic size of the drawable because the loaded drawable is different in size. Unfortunately I haven't seen this handled anywhere. The PicassoDrawable is the closest I've found – Kevin van Mierlo Jan 20 '20 at 15:19