簡體   English   中英

以編程方式更新android Vector Drawable

[英]programmatically update android Vector Drawable

我有一個 VectorDrawable 由 9 個矩形組成。 這在 drawables 文件夾中定義為 XML。 我將此設置為我在 xml 中聲明的 ImageView 的背景。 android:src="@drawable/squares00"我想在運行時以編程方式更改一個或多個方塊的顏色。 我知道有辦法使用 VectorDrawable 動畫來做到這一點。 但是我想知道是否有更簡單的方法可以在 java 中訪問我的 vectorDrawable,更新其屬性(為矩形設置一種或多種填充顏色),然后使用更新的 VectoDrawable 更新圖像背景。 我的目標是 Android API 21(棒棒糖)

簡而言之:

  1. 無法直接訪問VectorDrawable 中的內部元素。
  2. AnimatedVectorDrawable只能訪問內部元素。
  3. 使用AnimatedVectorDrawable來模擬你需要的東西。

長:

1.您沒有訪問權限

查看VectorDrawable源代碼將顯示內部元素信息存儲在內部私有狀態類VectorDrawableState 名稱公開內部元素的唯一方法是getTargetByName ,但不幸的是它是包私有的(默認) - 你不能使用它(除非你使用反射)。

2. AnimatedVectorDrawable只有訪問權限

getTargetByName僅被AnimatedVectorDrawable 使用,我們可以通過搜索該方法的用法來找到。

3. 使用AnimatedVectorDrawable

所以現在我們看到這是唯一可用的選項,例如,我們可以嘗試以下將元素“rect2”的顏色從白色更改為黑色:

change_color.xml:

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <objectAnimator
        android:duration="0"
        android:propertyName="fillColor"
        android:valueFrom="@color/white"
        android:valueTo="@color/black"/>
</set>

動畫.xml:

<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:drawable="@drawable/vectordrawable" >
    <target
        android:name="rect2"
        android:animation="@anim/change_color" />
</animated-vector>

並使用此處描述的方法。

筆記

如果以上仍然不適合您,您可以嘗試以下操作:

  • 復制整個VectorDrawable並調整它(未測試)
  • getTargetByName使用反射來獲取內部元素。 您需要確保首先mutate對象。

使用這個直接訪問內部元素。 這是實現這個答案

試試這個庫https://github.com/devendroid/VectorChildFinder

val vector = VectorChildFinder(context, R.drawable.drawable_id, imageView)
vector.findPathByName("path_name").fillColor = Color.RED

<vector
    ...>

    <path
        android:name="path_name"
        android:fillColor="#000"
        android:pathData="..." />
</vector>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM