/** * 绘制自动换行文本(默认最大3行,代码中的数字都是调试好的,不可轻举妄动!!) * * @param g {@link Graphics2D} * @param str 文本 * @param y 坐标Y * @param width 文字区域总宽度 * @param lineHeight 每行高度(为空时取字号大小) */ public static Integer drawWrapString(Graphics2D g, String str, int y, int width, Integer lineHeight) { Font font = g.getFont(); FontMetrics fontMetrics = new JLabel(str).getFontMetrics(font); if (lineHeight == null) { lineHeight = font.getSize(); } char[] chars = str.toCharArray(); List<StringBuilder> lines = new ArrayList<>(); int s = 0; StringBuilder p = null; for (char c : chars) { int cWidth = fontMetrics.stringWidth(c + ""); if (p == null || s + cWidth >= width) { p = new StringBuilder(); lines.add(p); s = cWidth; } else { s += cWidth; } p.append(c); } Integer maxLine = lines.size(); for (int i = 0; i < maxLine; i++) { int x1 = (width - g.getFontMetrics().stringWidth(lines.get(i).toString())/2); g.drawString(lines.get(i).toString(), x1, y + ((4 - maxLine + i) * (lineHeight))); } return maxLine; }
研究了好长时间,记下来,方便后来人
标签:Graphics2D,width,换行,lines,param,int,二维码,lineHeight,maxLine From: https://www.cnblogs.com/kaka945/p/18054097