本文介绍了带有矢量可绘制对象的TransitionDrawable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在xml中定义了这样的TransitionDrawable:

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)
    }
}

如果@drawable/ic_disabled@drawable/ic_enabledpng文件,则一切正常.但是,如果它们是矢量可绘制对象,则过渡将不起作用.我想念什么? TransitionDrawable不支持矢量可绘制对象吗?

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?

推荐答案

我知道这很旧,但是我遇到了同样的问题...您必须在将Vector转换为BitmapDrawable之前,再将其添加到TransitionDrawable中.这是一个例子

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...

实用程序方法//请参见 https://stackoverflow.com/a/38244327/114549

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;
}

这篇关于带有矢量可绘制对象的TransitionDrawable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 09:36