效果:

Java中使用Graphics2D绘制字符串文本自动换行 算法-LMLPHP

代码:

    /**
     * @return void
     * @Author xia
     * @Description //TODO 写字换行算法
     * @Date 18:08 2021/4/1
     * @Param []
     **/
    private static void drawWordAndLineFeed(Graphics2D g2d, Font font, String words, int wordsX, int wordsY, int wordsWidth) {
        FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font);
        // 获取字符的最高的高度
        int height = metrics.getHeight();

        int width = 0;
        int count = 0;
        int total = words.length();
        String subWords = words;
        int b = 0;
        for (int i = 0; i < total; i++) {
            // 统计字符串宽度 并与 预设好的宽度 作比较
            if (width <= wordsWidth) {
                width += metrics.charWidth(words.charAt(i)); // 获取每个字符的宽度
                count++;
            } else {
                // 画 除了最后一行的前几行
                String substring = subWords.substring(0, count);
                g2d.drawString(substring, wordsX, wordsY + (b * height));
                subWords = subWords.substring(count);
                b++;
                width = 0;
                count = 0;
            }
            // 画 最后一行字符串
            if (i == total - 1) {
                g2d.drawString(subWords, wordsX, wordsY + (b * height));
            }
        }
    }

调用:

      // 添加第二行文字
            Font fontTwo = new Font("MIMO天线及其空口测试技术", Font.BOLD, 140  );
            graphics.setFont(fontTwo);
            graphics.setColor(Color.WHITE);
            String textTwo = "MIMO天线及其空口测试技术";
            int twoX = 50; // 第二行文字起始x坐标
            int twoY = 480; // 第二行文字起始y坐标
            drawWordAndLineFeed(graphics, fontTwo, textTwo, twoX, twoY, 1200);
04-23 10:59