Wednesday, September 14, 2011

Simple crossfade on an ImageView

In a project I have this ListView where I initially display a list of items that each contain an ImageView with a drawable from the resources. In the background a thread is started to download the actual image and I wanted a crossfade as soon as I could set this downloaded image on the ImageView.

Basically what you need to do is create a new TransitionDrawable where the contents of layer 0 is the current drawable of the image view. And layer 1 will contain the new drawable to which you want to crossfade to. Last thing you need to do is to enable the crossfading, applying this newly created transition drawable on the image and starting the transition.

public static void setImageBitmapWithFade(final ImageView imageView, final Bitmap bitmap) {
 Resources resources = imageView.getResources();
 BitmapDrawable bitmapDrawable = new BitmapDrawable(resources, bitmap);
 setImageDrawableWithFade(imageView, bitmapDrawable);
}
        
public static void setImageDrawableWithFade(final ImageView imageView, final Drawable drawable) {
 Drawable currentDrawable = imageView.getDrawable();
 if (currentDrawable != null) {
  Drawable [] arrayDrawable = new Drawable[2];
  arrayDrawable[0] = currentDrawable;
  arrayDrawable[1] = drawable;
  TransitionDrawable transitionDrawable = new TransitionDrawable(arrayDrawable);
  transitionDrawable.setCrossFadeEnabled(true);
  imageView.setImageDrawable(transitionDrawable);
  transitionDrawable.startTransition(250);
 } else {
  imageView.setImageDrawable(drawable);
 }
}

No comments:

Post a Comment