根據api,很容易知道使用方式如下:
指定字符串和坐標即可。
但是簡單認為字符串的起始位置就是左上頂點就錯了,這樣畫起來每次的位置都不對,字體的大小不同,位置偏差很大。仔細看api注釋后發現,y坐標是字符串基線位置的坐標,也就是說字符串基線與畫布y重合。
字體的高由個元素組成:
ascent
descent
drawString中用的y坐標是指baseline的y坐標,即字體所在矩形的左上角y坐標+ascent
改進后的示例代碼:
BufferedImage srcBi = xxx; int owidth = srcBi.getWidth(); int oheight = srcBi.getHeight(); Graphics2D graphics = (Graphics2D)srcBi.getGraphics(); graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); graphics.setColor(Color.BLUE); int fontSize = 50; Font font = new Font("楷體",Font.BOLD,fontSize); graphics.setFont(font); FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font); //畫字符串,x坐標即字符串左邊位置,y坐標是指baseline的y坐標,即字體所在矩形的左上角y坐標+ascent graphics.drawString(DateUtil.formatDate(new java.util.Date(),DateUtil.FULL_TRADITION_PATTERN),10,10+metrics.getAscent()); //基線對齊改為頂邊對齊 String centerWords = "居中文字"; int strWidth = metrics.stringWidth(centerWords); int strHeight = metrics.getHeight(); int left = (owidth-strWidth)/2; //左邊位置 int top = (oheight-strHeight)/2+metrics.getAscent(); //頂邊位置+上升距離(原本字體基線位置對准畫布的y坐標導致字體偏上ascent距離,加上ascent后下移剛好頂邊吻合) graphics.drawString(centerWords,left,top);
效果圖