2

I have TransitionDrawable defined in xml like this:

transition.xml

<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_disabled" />
    <item android:drawable="@drawable/ic_enabled" />
</transition>

I use it to animate state changes of checkbox:

val stateDrawable = ContextCompat.getDrawable(this, R.drawable.transition) as TransitionDrawable
checkbox.buttonDrawable = stateDrawable
checkbox.setOnCheckedChangeListener { icon, checked -> 
    if (checked) {
        stateDrawable.startTransition(300) 
    } else {
        stateDrawable.reverseTransition(300)
    }
}

If @drawable/ic_disabled and @drawable/ic_enabled are png files, everything works fine. But if they are vector drawables, transition doesn't work. What am I missing? Does TransitionDrawable not support vector drawables?

mol
  • 2,607
  • 4
  • 21
  • 40
  • You might want to take a look in [VectorDrawables](https://developer.android.com/reference/android/graphics/drawable/VectorDrawable.html) if you are using vectors. – Abhi Apr 11 '18 at 14:54
  • @Abhi Sure, I'm already using them. The question is there a way to use them in `TransitionDrawable` to create crossfading animation between two vector drawables. – mol Apr 12 '18 at 06:31
  • @mol Have you found a solution? – Yuliya Tarasenko Jul 21 '18 at 17:55
  • @YuliyaTarasenko Unfortunatelly no, I ended up using `.png` files. – mol Jul 23 '18 at 06:19

3 Answers3

5

I know this is old, but I had the same issue... You gotta convert the Vector to a BitmapDrawable before adding to the TransitionDrawable. Here's an example

            TransitionDrawable td = new TransitionDrawable(new Drawable[]{
                    getBitmapDrawableFromVectorDrawable(this, R.drawable.vector1),
                    getBitmapDrawableFromVectorDrawable(this, R.drawable.vector2)
            });
            td.setCrossFadeEnabled(true); // probably want this

            // set as checkbox button drawable...

Utility Methods // see https://stackoverflow.com/a/38244327/114549

public static BitmapDrawable getBitmapDrawableFromVectorDrawable(Context context, int drawableId) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        return (BitmapDrawable) ContextCompat.getDrawable(context, drawableId);
    }
    return new BitmapDrawable(context.getResources(), getBitmapFromVectorDrawable(context, drawableId));
}

public static Bitmap getBitmapFromVectorDrawable(Context context, int drawableId) {
    Drawable drawable = ContextCompat.getDrawable(context, drawableId);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        drawable = (DrawableCompat.wrap(drawable)).mutate();
    }

    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
            drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);

    return bitmap;
}
aaronvargas
  • 12,189
  • 3
  • 52
  • 52
2

Since all I wanted was to change the image with fade, I implemented a simple version of TransitionDrawable that seem to work for fixed size vector drawables.

public class SimpleTransitionDrawable extends Drawable {
    private static final int TRANSITION_STARTING = 0;
    private static final int TRANSITION_RUNNING = 1;
    private static final int TRANSITION_NONE = 2;

    private int state = TRANSITION_NONE;

    private long startTimeMillis;
    private int duration;

    private @Nullable Drawable source;
    private Drawable target;

    public void setTarget(Drawable target) {
        this.source = this.target;
        this.target = target;
        target.setBounds(0, 0, target.getIntrinsicWidth(), target.getIntrinsicHeight());
    }

    public void startTransition(int durationMillis) {
        duration = durationMillis;
        state = TRANSITION_STARTING;
        invalidateSelf();
    }

    @Override
    public void draw(Canvas canvas) {
        int alpha;

        switch (state) {
            case TRANSITION_STARTING:
                startTimeMillis = SystemClock.uptimeMillis();
                alpha = 0;
                state = TRANSITION_RUNNING;
                break;

            case TRANSITION_RUNNING:
                float normalized = (float) (SystemClock.uptimeMillis() - startTimeMillis) / duration;
                alpha = (int) (0xff * Math.min(normalized, 1.0f));
                break;

            default:
                if (target == null) return;
                alpha = 0xff;
                break;
        }

        if (source != null && alpha < 0xff) {
            source.setAlpha(0xff - alpha);
            source.draw(canvas);
        }

        if (alpha > 0) {
            target.setAlpha(alpha);
            target.draw(canvas);
        }

        if (alpha == 0xff) {
            state = TRANSITION_NONE;
            return;
        }

        invalidateSelf();
    }

    @Override public void setAlpha(int alpha) {}

    @Override public void setColorFilter(ColorFilter colorFilter) {}

    @Override public int getOpacity() {return PixelFormat.TRANSLUCENT;}
}

Initialize it like this:

ImageView view = findViewById(R.id.image_view);
SimpleTransitionDrawable drawable = new SimpleTransitionDrawable();
view.setImageDrawable(drawable);

Then change the drawable with fade:

drawable.setTarget(AppCompatResources.getDrawable(this, R.drawable.my_vector));
drawable.startTransition(350);
squirrel
  • 5,114
  • 4
  • 31
  • 43
1

Following the same approach made by @aaronvargas https://stackoverflow.com/a/54583929/1508956

I've created some extensions function which encapsulate the implementation and also makes easier the usability

fun Drawable.getBitmapDrawableFromVectorDrawable(context: Context): BitmapDrawable {
    return BitmapDrawable(context.resources, getBitmapFromVectorDrawable())
}

fun Drawable.getBitmapFromVectorDrawable(): Bitmap {
    val bitmap = Bitmap.createBitmap(
        intrinsicWidth,
        intrinsicHeight, Bitmap.Config.ARGB_8888
    )

    val canvas = Canvas(bitmap)
    setBounds(0, 0, canvas.width, canvas.height)
    draw(canvas)

    return bitmap
}

fun ImageView.setTransitionDrawable(vectorID: Int, firstColor: Int, secondColor: Int): TransitionDrawable? {
    val drawables = arrayOfNulls<Drawable>(2)

    val firstDrawable = ContextCompat.getDrawable(context, vectorID) ?: return null
    DrawableCompat.setTint(firstDrawable, ContextCompat.getColor(context, firstColor))
    drawables[0] = firstDrawable.getBitmapDrawableFromVectorDrawable(context)

    val secondDrawable = ContextCompat.getDrawable(context, vectorID) ?: return null
    DrawableCompat.setTint(secondDrawable, ContextCompat.getColor(context, secondColor))
    drawables[1] = secondDrawable.getBitmapDrawableFromVectorDrawable(context)

    val transition = TransitionDrawable(drawables)
    transition.isCrossFadeEnabled = true
    setImageDrawable(transition)

    return transition
}

Initialization:

val transition = imageView.setTransitionDrawable(resourceID, R.color.firstColor, R.color.secondColor)
transition?.startTransition(3000)
rodrigosimoesrosa
  • 1,719
  • 1
  • 12
  • 16