填充字符串中的字符

时间:2016-11-10 09:05:15

标签: java swing fonts

我有一个java应用程序,我在其中绘制一个字符串。

enter image description here

现在我想调整它们适合网格的每个字符前后的空白区域(每个字符在它们自己的方格中)。我怎么能做到这一点?谢谢您的回答。

public class FontTesting extends Applet {

private final int gridSize=20;
public void paint(Graphics g) {

    Graphics2D g2d = (Graphics2D)g;
    paintBackground(g2d);
    String text1 = "atzlipjnmr . . A|";
    String text2 = "HHHHHHHHHH . . I|";
    String text3 = "WWWWWWWWWW , , 9|";
    String text4 = "ATATATATAT      |";
    Font font = new Font("monospaced", Font.PLAIN, 20);

    g2d.setColor(Color.BLACK);
    g2d.setFont(font);

    g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
            RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g2d.drawString(text1, 20, 36);

    g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                         RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g2d.drawString(text2.toUpperCase(), 20, 56);

    g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
            RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g2d.drawString(text3.toUpperCase(), 20, 76);

    g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
            RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g2d.drawString(text4.toUpperCase(), 20, 96);
}

public static void main(String[] args) {

    Frame f = new Frame("Antialiased Text Sample");

    f.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

    f.add(new FontTesting());
    f.setBackground(Color.WHITE);
    f.setSize(new Dimension(300, 180));
    f.setVisible(true);
}
private void paintBackground(Graphics2D g2){
    g2.setPaint(Color.GRAY);
    for (int i = 0; i < getSize().width; i += gridSize) {
      Shape line = new Line2D.Float(i, 0, i, getSize().height);
      g2.draw(line);
    }

    for (int i = 0; i < getSize().height; i += gridSize) {
      Shape line = new Line2D.Float(0, i, getSize().width, i);
      g2.draw(line);
    }
}

}

1 个答案:

答案 0 :(得分:2)

将字符字符串逐字符绘制到网格中。看看这个方法。

private void paintText(Graphics2D g2, int row, String text){
    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    for(int i = 0; i < text.length(); i++){
        g2.drawString(Character.toString(text.charAt(i)), i * gridSize, row * gridSize);   
    }  
}

你可以在paint()这样的算法中使用它。

paintText(g2d, 1, text1);
paintText(g2d, 2, text2);
[...]