【问题标题】:Rotate between colors in String在字符串中的颜色之间旋转
【发布时间】:2017-04-08 03:16:31
【问题描述】:

我正在尝试创建一个旋转颜色的String。每个字母都有不同的color,它们需要以线性方式旋转。文本将进入JLabel

我构建了文本,以便可以在给定一个单词和一组颜色(字符串)的情况下创建它。

String[] colors = {"white", "blue", "red"};
String word = "foo";
String coloredText;

String[] letters = word.split("(?!^)"); //split text into indiv. letters

        coloredText = "<html>";

        for(int i = 0, j = 0; i < letters.length; i++, j++){

            if(j >= colors.length)
                j=0;

            coloredText += String.format("<font color='%s'> %s </font>", colors[j], letters[i]);
        }

        coloredText += "</html>";

这将产生一个字符串,其 foo 带有白色 F、蓝色 O 和红色结尾 O

当然,如果颜色少于字母,它们会继续旋转。

现在我有一个 timer 来旋转颜色,但我不知道 algorithm 来做这件事。 基本上,每种颜色都应替换下一种颜色,最后一种颜色替换第一种颜色。

例如:

当然,这必须适用于任意数量的给定字母和颜色,不适合的颜色会被忽略。 (3个字母10种颜色的单词只会使用前3种颜色)。

我尝试过使用.replace(),但regex 对我来说有点太难了。

有什么想法吗?

【问题讨论】:

  • 保留用于字段中第一个字母的颜色索引,并在每次为字符串着色时递减它。如果达到 -1,则将其重置为最后一个索引。第一轮是 0,所以你最终得到 WBR。然后你递减它。因为它变成-1,你把它设置为2,你最终得到RWB。然后将其递减,最终得到 BRW。

标签: java string algorithm colors


【解决方案1】:

您可以有一个额外的整数(类或实例变量,取决于您的代码)作为 0 和 colors.length-1 之间的偏移计数器。

int offset = 0

每次执行计时器时,将偏移量增加 1 并检查您的偏移量是否超出允许的偏移量。如果是这样,请将其重置为 0。

void onTimerExecutes(){
    offset++;
    if (offset >= colors.length)
        offset = 0;
    applyColorsToText();
}

然后将偏移量添加到您的j:

j = offset;
for(int i = 0, i < letters.length; i++, j++)

【讨论】:

  • 偏移量应该减少以旋转 OP 想要的方式
【解决方案2】:

或者,如果您不将偏移量重置为 0,而是使用模数运算符对数组进行索引,则可以跳过一些行。见Modulus Operator

所以你有

void onTimerExecutes(){
offset++;
applyColorsToText();
}

在for循环中

            coloredText += String.format("<font color='%s'> %s </font>",    colors[offset%colors.length], letters[i]);

如果您想反向旋转,请减少偏移量:

offset = 0;
void onTimerExecutes(){
offset--;
applyColorsToText();
}

并使用Math.floorMod(int, int),所以:

            coloredText += String.format("<font color='%s'> %s </font>",    colors[Math.floorMod(offset, colors.length)], letters[i]);

【讨论】:

    猜你喜欢
    • 2021-12-08
    • 1970-01-01
    • 2012-03-30
    • 2023-04-10
    • 2012-11-27
    • 2011-03-24
    • 2011-02-20
    • 2010-10-21
    相关资源
    最近更新 更多