废话不多说了,直接上代码。
public class demol_NewDrawi { public static void main(String[] args) throws Exception { int width = 150; int height = 30; String out = "今夕是何年?"; double rate = 0.90; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); Graphics g = image.getGraphics(); //创霆画笔 g.setColor(new Color(200, 192, 184));//背景颜色 g.fill3DRect(0,0, width, height, true); g.setColor(Color.BLACK);//文字颜色 g.setFont(new Font("宋体", Font.BOLD, 20));//设盟宁体 //居中显示 int x = (int) (width / 2 - rate * g.getFontMetrics().stringWidth(out) / 2); int y = height / 2 + g.getFontMetrics().getHeight() / 3; MyDrawString(out, x, y, rate, g); ImageIO.write(image, "png", new File("d : / 2.png")); } public static void MyDrawString(String str, int x, int y, double rate, Graphics g) { String tempstr = new String(); int orgstringwight = g.getFontMetrics().stringWidth(str); int orgstringLength = str.length(); int tempx = x; int tempy = y; while (str.length() > 0) { tempstr = str.substring(0, 1); str = str.substring(1, str.length()); g.drawString(tempstr, tempx, tempy); tempx = (int) (tempx + (double) orgstringwight / (double) orgstringLength * rate); } } }
FontMetrics属性的介绍
1.基准点是baseline
2.ascent:是baseline之上至字符最高处的距离
3.descent:是baseline之下至字符最低处的距离
4.leading:是上一行字符的descent到下一行的ascent之间的距离,也就是相邻行间的空白距离
5.top:是指的是最高字符到baseline的值,即ascent的最大值
6.bottom:是指最低字符到baseline的值,即descent的最大值