Java中使用Graphics2D实现字符串- 竖直并居中排序显示算法

效果:

代码:

    public static void drawMyString(Graphics textGraphics, String text) {

        // 每列显示的汉字数量
        int columnSize = 7;
        // 文字之间的垂直间距
        int verticalSpacing = 75;

        // 获取字体渲染上下文
        FontMetrics fm = textGraphics.getFontMetrics();
        // 获取字体的高度
        int fontHeight = fm.getHeight();
        System.out.println(fontHeight);
        // 计算每列的宽度
        int columnWidth = fontHeight + verticalSpacing;

        // 设置初始位置
        int x = 260;
        int y = 450;
        Font fontFour = new Font(" Source Han Sans CN", Font.BOLD, 100);
        textGraphics.setFont(fontFour);

        Color color = new Color(0, 88, 38);
        textGraphics.setColor(color);
//        // 绘制文字
        int charCount = 0;
        int totalColumns = (int)Math.ceil((double)text.length() / columnSize); // 总列数
        int totalRows = Math.min(columnSize, text.length()); // 总行数
        int remainingChars = text.length() % columnSize; // 最后一列剩余字符数

        for (int columnIndex = 0; columnIndex < totalColumns; columnIndex++) {
            for (int rowIndex = 0; rowIndex < totalRows; rowIndex++) {
                if (charCount >= text.length()) break;
                char ch = text.charAt(charCount);
//                // 计算当前位置
                int cx = x - columnIndex * columnWidth;
                int cy = y + rowIndex * fontHeight + rowIndex * verticalSpacing; // 加入垂直偏移量
// 计算当前位置
//                int cx = x - columnIndex * columnWidth;
//                int cy = y + rowIndex * fontHeight + rowIndex * verticalSpacing + columnIndex ;

                // 如果是最后一列并且不满 7 个字符,则需要将剩余字符居中
                if (columnIndex == totalColumns - 1 && remainingChars > 0) {
                    int extraVerticalSpace = (columnSize - remainingChars) * (fontHeight + verticalSpacing) / 2;
                    cy += extraVerticalSpace;
                }

                // 绘制文字
                textGraphics.drawString(String.valueOf(ch), cx, cy);
                charCount++;
            }
        }

    }

调用:
 

        // TODO 讲座名称
        String lectureName = "时空相分离调控的职务细胞信号转导";
        drawMyString(graphics, lectureName);

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大大怪~将军

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值