在Java中更改字体和绘制字符串的正确语法是什么?

在Java中更改字体和绘制字符串的正确语法是什么?,java,graphics,drawstring,fontmetrics,Java,Graphics,Drawstring,Fontmetrics,有人能检查一下我的语法吗?我将“Times New Roman”、“Arial”、“Verdana”传递给fontName,并将8、12、15等用于fontSize。它永远不会改变这里的字体。我这样做是为了在图像上写一些文字 Graphics2D g2d = (Graphics2D) bufferedImage.getGraphics(); g2d.drawImage(photo, 0, 0, null); g2d.setColor(Color.white); Font font = new F

有人能检查一下我的语法吗?我将“Times New Roman”、“Arial”、“Verdana”传递给
fontName
,并将8、12、15等用于
fontSize
。它永远不会改变这里的字体。我这样做是为了在图像上写一些文字

Graphics2D g2d = (Graphics2D) bufferedImage.getGraphics();
g2d.drawImage(photo, 0, 0, null);
g2d.setColor(Color.white);
Font font = new Font(fontName, Font.PLAIN, fontSize);
g2d.setFont(font);
g2d.drawString(text,x,y);

你应该这样做

BufferedImage img = new BufferedImage(
    w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
g2d.drawImage(photo, 0, 0, null);
g2d.setPaint(Color.red);
//example :     g2d.setFont(new Font("Serif", Font.BOLD, 15));
g2d.setFont(new Font(fontName, Font.BOLD, size));
String s = "Hello, world!";
// assuming x & y is set using graphic's font metrics
g2d.drawString(s, x, y);
g2d.dispose();
摘自sun文档

getGraphics

公共图形getGraphics()此 方法返回一个Graphics2D,但为 这里是向后兼容性。 createGraphics更方便, 因为它被声明为返回一个 图形2d


这并不意味着您不应该使用
getGraphics
API。只是上面的代码对我有效:)

我最终发现系统上没有我列表中的字体,所以我必须使用getAllFonts()方法,只传递列表中的字体