0

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.

zhangxaochen
  • 32,744
  • 15
  • 77
  • 108
C2C
  • 85
  • 6

2 Answers2

2

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);
}
Kanak Sony
  • 1,570
  • 1
  • 21
  • 37
0

You can also set the element color by referring to the following code:

ShapeElement shapeElementWhite = new ShapeElement();

shapeElementWhite.setRgbColor(new RgbColor(255,255,255)); // Set Color Using Numbers

shapeElementWhite.setRgbColor(RgbColor.fromArgbInt(0xADD8E6)); // Set Color Using Hexadecimal

Component component = findComponentById(ResourceTable.Id_buy_train);

component.setBackground(shapeElementWhite);
zhangxaochen
  • 32,744
  • 15
  • 77
  • 108
  • Thanks for reply, But this solution is not working for me, because in my case Element is type of VectorElement or PixleMapElement. – C2C Aug 17 '21 at 12:14