如何使用drawString更改String中单个字符的颜色?

时间:2014-01-24 11:14:08

标签: java graphics colors awt java-2d

我在使用drawString()时遇到了一个问题。我正在制作像zType这样的游戏,我在drawString()时遇到了这个问题。如何在drawString()移动时更改角色的字体颜色?

3 个答案:

答案 0 :(得分:3)

现在您已经明确表示只想绘制特定颜色的字符串中的某些字符(这是您的问题中应该提到的重要细节),您可以像其他人提到的那样计算这些字符的字体指标。

但是,绘制单个连续字符串可能不仅仅是FontMetrics,例如字距调整,甚至连接某些脚本和字体中的字母。相反,我会使用AttributedCharacterIterator。

获取AttributedCharacterIterator的最简单方法是创建AttributedString

AttributedString a = new AttributedString(text);

// We want first two characters drawn in red.
a.addAttribute(TextAttribute.FOREGROUND, Color.RED, 0, 2);

graphics.drawString(a.getIterator(), x, y);

答案 1 :(得分:1)

调用Graphics.setColor(),如下所示,

public void paint (Graphics g) {
   g.setColor(Color.RED);
   g.drawString("Hello World!!", 50, 100);
}

如果你只希望第一个角色有不同的颜色,那么你应该做这样的事情,

public void paint(Graphics g) {
   Color prev = g.getColor();
   g.setColor(Color.RED);
   g.drawString("H", 50, 100);
   FontMetrics metrics = g.getFontMetrics();
   int width = metrics.stringWidth("H");
   g.setColor(prev);
   g.drawString("ello World!!", 50 + width, 100);
}

答案 2 :(得分:1)

您需要使用FontMetrics来获取H的宽度,并将该宽度添加到x的{​​{1}}点

ello

enter image description here

    Font font = new Font("impact", Font.PLAIN, 50);
    FontMetrics fm = g.getFontMetrics(font);
    int widthH = fm.stringWidth("H");
    g.setFont(font);

    g.setColor(Color.BLUE);
    g.drawString("H", 100, 100);

    g.setColor(Color.RED);
    g.drawString("ello", 100 + widthH, 100);
相关问题