TransitionDrawable with vector drawables

前端 未结 2 1524
南旧
南旧 2021-01-15 20:00

I have TransitionDrawable defined in xml like this:

transition.xml


<         


        
2条回答
  •  伪装坚强ぢ
    2021-01-15 20:26

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

提交回复
热议问题