如何在绘图时将字母分隔成字符串

时间:2015-01-13 19:34:49

标签: java draw drawstring

我想画一个从jtextarea中取出的字符串,但是我想用每个字母的20px空间绘制,但我想我不能用抽绳来做这个,我不能画一个每次使用抽奖器,所以我能做什么?

我想在每条痕迹上面写一封信,但我知道如何知道不起作用

public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    for(int i=0;i<PalavraAdivinha.length();i++)
    {
        g.fillRect(InicioTraco+(i*40), 240, 40, 5);
    }
    Font titulo = new Font("Arial",Font.BOLD,40);
    g.setFont(titulo);
    g.drawString("Adivinhe a palavra", 0,100 );
    if(PalavraDigitada != null)
    {
        g.drawString(PalavraDigitada, InicioTraco, 235);
    }
}
谢谢你。

1 个答案:

答案 0 :(得分:2)

您可以单独绘制每个角色。通过检索FontMetrics对象当前使用的Graphics,您可以测量每个字符的宽度,以便您可以使用此宽度和给定的分隔。

public static void drawString(Graphics g, String string, int x, int y,
        int seperation) {

    FontMetrics metrics = g.getFontMetrics();
    int drawx = x;

    for (int i = 0; i < string.length(); ++i) {
        String character = "" + string.charAt(i);

        g.drawString(character, drawx, y);
        drawx += seperation + metrics.stringWidth(character);
    }
}

示例代码

public static void main(String[] args) throws IOException {
    BufferedImage image = new BufferedImage(512, 256,
            BufferedImage.TYPE_INT_ARGB);
    Graphics g = image.getGraphics();
    g.setColor(Color.BLACK);
    for (int i = 0; i < 10; ++i)
        drawString(g, "i am drawn with seperation " + i, 24, 24 + 16 * i, i);
    ImageIO.write(image, "png", new File("output.png"));
}

<强>结果

Several strings with increasing amounts of seperation