0

我正在使用 Java SDK 在 HarmonyOS 中创建一个自定义组件,我需要在运行时更改元素颜色。

在 Android 中,我们有setTint()api 可以在运行时更改 drawable 的颜色。

例如:

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

但是,在 HMOS 中,我看到没有任何类似setTint()setColor()更改元素颜色的 api。

4

2 回答 2

2

setColorMatrix您可以使用类更改图标的颜色Element

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);
}
于 2021-07-28T09:35:41.053 回答
0

也可以参考以下代码设置元素颜色:

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);
于 2021-07-29T01:01:48.767 回答