0

In the code I am calling diamond.xml with this string:

private final Drawable diamond = context.getResources().getDrawable(R.drawable.diamond);

I draw that with this code:

diamond.setBounds(0, 0, 10, 10);
diamond.draw(canvas);

In some cases, I need to draw that just changing one or both of the android:fillColor. Is it possible? I would like to avoid to create N copies of diamond.xml with all the combinations of colors.

diamond.xml

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:height="100dp" android:width="70dp"
    android:viewportHeight="100" android:viewportWidth="100">

    <path
        android:fillColor="#FF5722"
        android:pathData="M 5,5 95,5 95,95 5,95 z"
        android:strokeAlpha="1"
        android:strokeColor="#FFFFFF"
        android:strokeLineCap="butt"
        android:strokeLineJoin="round"
        android:strokeWidth="4"/>

    <path
        android:fillColor="#8BC34A"
        android:pathData="m 50,30 l 20,20 -20,20 -20,-20 z"
        android:strokeAlpha="1"
        android:strokeColor="#FFFFFF"
        android:strokeLineCap="butt"
        android:strokeLineJoin="round"
        android:strokeWidth="4"/>

</vector>
Stefano
  • 209
  • 2
  • 10
  • 34
  • There is an attribute tint, try with it once – akashzincle Apr 13 '20 at 16:59
  • I wonder how would you do that if you have two paths with two different colors – vrgrg Apr 13 '20 at 17:03
  • yeah you are right, but if u are not getting any direction, u can try once, maybe it recolors all the path, i have tried for images with one path, it worked for them – akashzincle Apr 13 '20 at 17:08
  • You can create themes for all the color combinations and set them to the same drawable XML as described here https://stackoverflow.com/questions/33126904/change-fillcolor-of-a-vector-in-android-programmatically – vrgrg Apr 13 '20 at 17:11

2 Answers2

0

dont use android:fillColor to change value. you can use android:tint="YOUR_COLOR"

suhas sasuke
  • 640
  • 6
  • 7
0

Create the themes and set colours inside it,

<style name="UpdatedScene" parent="DefaultScene">
<item name="diamond_red">#red_color_hex</item>
</style>

and then create the drawable with this theme,

final ContextThemeWrapper wrapper = new ContextThemeWrapper(this,R.style.DefaultScene);
final Drawable drawable = ResourcesCompat.getDrawable(getResources(),R.drawable.diamond, wrapper.getTheme());
imageView.setImageDrawable(drawable);

Default scene would be your default color to the drawable. while changing the color set the different theme.

Prashant.J
  • 739
  • 7
  • 12
  • thanks but I have not clear it. Should I edit diamond.xml or it is ok in this way? How can I specify if change the color of the first path or of the second? – Stefano Apr 14 '20 at 09:21