嵌入TTF并与g2d一起使用

时间:2013-08-27 06:04:02

标签: java graphics fonts drawstring

我正在尝试嵌入TTF字体,然后使用Grapics2D绘制它。我已经能够创建字体,但我不确定如何将字体传递给setFont。我在这里制作了一个新字体,这没有例外:

private Font pixel = Font.createFont(Font.TRUETYPE_FONT, this.getClass().getResourceAsStream("font/amora.ttf"));

但我无法弄清楚如何用setFont();

绘制它

这是我的代码:

private static final long serialVersionUID = 1L;
private Timer timer;
private Char Char;
private Font pixel = Font.createFont(Font.TRUETYPE_FONT, this.getClass().getResourceAsStream("font/amora.ttf")); <<<--------

public Board() throws FontFormatException, IOException {

    addKeyListener(new TAdapter());
    setFocusable(true);
    setBackground(Color.BLACK);
    setDoubleBuffered(true);

    Char = new Char();

    timer = new Timer(5, this);
    timer.start();
}


public void paint(Graphics g) {
    super.paint(g);

    Graphics2D g2d = (Graphics2D)g;
    g2d.drawImage(Char.getImage(), Char.getX(), Char.getY(), this);
    g.setColor(Color.white);
    g.setFont( What goes here? );  // <------------
    g.drawString("Amora Engine rev25 (acetech09)", 10, 20);
    g.drawString(Char.getDebugStats(0), 10, 40);
    g.drawString(Char.getDebugStats(1), 10, 60);
    Toolkit.getDefaultToolkit().sync();
    g.dispose();
}


public void actionPerformed(ActionEvent e) {
    Char.move();
    repaint();  
}
}

非常感谢任何帮助。感谢。

2 个答案:

答案 0 :(得分:0)

你可以做......

g.setFont(pixel);

但你可能会有更好的成功

g.setFont(pixel.deriveFont(Font.BOLD, 36f));

是......的变种。

此外,请勿处置您未创建的Graphics上下文...

Graphics2D g2d = (Graphics2D)g;
/*...*/
// g.dispose();

或者

Graphics2D g2d = (Graphics2D)g.create();
/*...*/
g.dispose();

我也厌恶覆盖paint方法。假设您使用JComponentJPanel之类的内容,则应使用paintComponent。如果你直接渲染一个顶级容器(如JFrame),那我就不会。双缓冲和框架边框存在问题,这些问题不会让您的生活充满乐趣......

我也关注new Timer(5, this) - 5毫秒足够接近0,差别不大。你会更喜欢像40这样的东西,它可以给你25fps或17这样的东西,它会给你大约60fps ......

答案 1 :(得分:0)

应该是

g.setFont( this.pixel );

如果这不起作用,请尝试:

  1. 评论setFont指令。
  2. 使用对Java标准字体的引用替换Font.createFont
  3. 排除可能的问题。

相关问题