Search code examples
javaandroidhuawei-mobile-serviceshuawei-developersharmonyos

How to change Element color in HarmonyOS?


I am creating a custom component in HarmonyOS using Java SDK, Where I need to change Element color at runtime.

In Android we have setTint() api to change color of drawable at runtime.

for ex:

drawable.setTint(Color.BLUE); //Require Api level 21
OR
DrawableCompat.setTint(drawable, Color.BLUE);

but, In HMOS I saw there is no any api like setTint() or setColor() to change color of Element.


Solution

  • You can change the color of the icon using setColorMatrix from the Element class.

    public static void setIconColor(Element icon, Color color) {
        int iColor = color.getValue();
        int red   = (iColor & 0xFF0000) / 0xFFFF;
        int green = (iColor & 0xFF00) / 0xFF;
        int blue  = iColor & 0xFF;
        float[] matrix = {
                0, 0, 0, 0, red,
                0, 0, 0, 0, green,
                0, 0, 0, 0, blue,
                0, 0, 0, 1, 0 };
        ColorMatrix colorMatrix = new ColorMatrix();
        colorMatrix.setMatrix(matrix);
        icon.setColorMatrix(colorMatrix);
    }