我可以通过编程方式更改矢量可绘制对象的颜色,但是我想将笔触应用于矢量可绘制对象。我需要一种可以在运行时更改矢量可绘制笔触的方法:

android - 通过编程将Border/Stroke设置为Vector Drawable-LMLPHP

以前我使用这种方法,但在我的情况下失败了。

我将Vector drawable转换为位图,然后使用此功能应用边框,但是它全部用黑色填充,不应用笔触。

  private static Bitmap getBitmap(VectorDrawable vectorDrawable)
    {
        Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
        vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        vectorDrawable.draw(canvas);
        return bitmap;
    }
    private static Bitmap getBitmap(Context context, int drawableId)
    {

        Drawable drawable = ContextCompat.getDrawable(context, drawableId);
        if (drawable instanceof BitmapDrawable)
        {
            return ((BitmapDrawable) drawable).getBitmap();
        }
        else if (drawable instanceof VectorDrawable)
        {
            return getBitmap((VectorDrawable) drawable);
        }
        else
        {
            throw new IllegalArgumentException("unsupported drawable type");
        }
    }
private Bitmap addWhiteBorder(Bitmap bmp, int borderSize)
    {
        Bitmap bmpWithBorder = Bitmap.createBitmap(bmp.getWidth() + borderSize*2 , bmp.getHeight() + borderSize*2 , bmp.getConfig());
        Canvas canvas = new Canvas(bmpWithBorder);
        canvas.drawColor(Color.BLACK);
        canvas.drawBitmap(bmp, borderSize, borderSize, null);
        return bmpWithBorder;
    }

最佳答案

假设您在vectordrawable.xml中定义了VectorDrawable

<vector
    android:width="100dp"
    android:height="100dp"
    android:viewportWidth="100"
    android:viewportHeight="100">
    <path
        android:name="headset"
        android:strokeColor="#FF000000"
        android:strokeWidth="0"
        ...
        android:pathData="..." />
</vector>

然后,您可以定义一个AnimatedVectorDrawable来更改strokeWidth
<?xml version="1.0" encoding="utf-8"?>
<animated-vector
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/vectordrawable">
    <target
        android:animation="@animator/change_stroke_width"
        android:name="headset" />

</animated-vector>

最后,在change_stroke_width.xml中定义更改strokeWidth的动画:
<set xmlns:android="http://schemas.android.com/apk/res/android" >
    <objectAnimator
        android:duration="100"
        android:propertyName="strokeWidth"
        android:valueFrom="0"
        android:valueTo="10" />
</set>

09-28 14:26