使用 Java Graphics2D API 在 TextLayout 中将文本右对齐

2024-03-30

因此,我正在使用 Java 教程中的代码来绘制一段文本,但我不知道如何将文本与右边距对齐。

我刚刚包括attstring.addAttribute(TextAttribute.RUN_DIRECTION, TextAttribute.RUN_DIRECTION_RTL);在这种情况下的代码中,但它不起作用。

protected float drawParagraph (Graphics2D g2, String text, float width, float x, float y, Boolean dir){
        AttributedString attstring = new AttributedString(text);
        attstring.addAttribute(TextAttribute.FONT, font);
        if (dir == TextAttribute.RUN_DIRECTION_RTL){
            attstring.addAttribute(TextAttribute.RUN_DIRECTION, TextAttribute.RUN_DIRECTION_RTL);
        }
        AttributedCharacterIterator paragraph = attstring.getIterator();
        int paragraphStart = paragraph.getBeginIndex();
        int paragraphEnd = paragraph.getEndIndex();
        FontRenderContext frc = g2.getFontRenderContext();
        LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(paragraph, frc);

        // Set break width to width of Component.
        float breakWidth = width;
        float drawPosY = y;
        // Set position to the index of the first character in the paragraph.
        lineMeasurer.setPosition(paragraphStart);

        // Get lines until the entire paragraph has been displayed.
        while (lineMeasurer.getPosition() < paragraphEnd) {
            // Retrieve next layout. A cleverer program would also cache
            // these layouts until the component is re-sized.
            TextLayout layout = lineMeasurer.nextLayout(breakWidth);
            // Compute pen x position. If the paragraph is right-to-left we
            // will align the TextLayouts to the right edge of the panel.
            // Note: drawPosX is always where the LEFT of the text is placed.
            float drawPosX = (float) (layout.isLeftToRight()
                        ? x : breakWidth - layout.getAdvance());

            // Move y-coordinate by the ascent of the layout.
            drawPosY += layout.getAscent();

            // Draw the TextLayout at (drawPosX, drawPosY).
            layout.draw(g2, drawPosX, drawPosY);

            // Move y-coordinate in preparation for next layout.
            drawPosY += layout.getDescent() + layout.getLeading();
        }
        return drawPosY;
    }

请帮忙,我迷路了^^


错误在于计算drawPosX。工作公式为drawPosX = (float) x + breakWidth - layout.getAdvance();

我最终做了一些修复来支持中心对齐,代码如下:

public abstract class MyClass extends JPanel implements Printable{

    [...]

    public static enum Alignment {RIGHT, LEFT, CENTER};

    [...]

    /**
 * Draw paragraph.
 * Pinta un parrafo segun las localizaciones pasadas como parametros.
 *
 * @param g2 Drawing graphic.
 * @param text String to draw.
 * @param width Paragraph's desired width.
 * @param x Start paragraph's X-Position.
 * @param y Start paragraph's Y-Position.
 * @param dir Paragraph's alignment.
 * @return Next line Y-position to write to.
 */
protected float drawParagraph (Graphics2D g2, String text, float width, float x, float y, Alignment alignment){
    AttributedString attstring = new AttributedString(text);
    attstring.addAttribute(TextAttribute.FONT, font);
    AttributedCharacterIterator paragraph = attstring.getIterator();
    int paragraphStart = paragraph.getBeginIndex();
    int paragraphEnd = paragraph.getEndIndex();
    FontRenderContext frc = g2.getFontRenderContext();
    LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(paragraph, frc);

    // Set break width to width of Component.
    float breakWidth = width;
    float drawPosY = y;
    // Set position to the index of the first character in the paragraph.
    lineMeasurer.setPosition(paragraphStart);

    // Get lines until the entire paragraph has been displayed.
    while (lineMeasurer.getPosition() < paragraphEnd) {
        // Retrieve next layout. A cleverer program would also cache
        // these layouts until the component is re-sized.
        TextLayout layout = lineMeasurer.nextLayout(breakWidth);
        // Compute pen x position. 
        float drawPosX;
        switch (alignment){         
        case RIGHT:
            drawPosX = (float) x + breakWidth - layout.getAdvance();
            break;
        case CENTER:
            drawPosX = (float) x + (breakWidth - layout.getAdvance())/2;
            break;
        default: 
            drawPosX = (float) x;
        }
        // Move y-coordinate by the ascent of the layout.
        drawPosY += layout.getAscent();

        // Draw the TextLayout at (drawPosX, drawPosY).
        layout.draw(g2, drawPosX, drawPosY);

        // Move y-coordinate in preparation for next layout.
        drawPosY += layout.getDescent() + layout.getLeading();
    }
    return drawPosY;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Java Graphics2D API 在 TextLayout 中将文本右对齐 的相关文章

随机推荐

  • Facebook 图表 API 与营销 API

    有人可以解释一下 facebook 的图表 API 和营销 API 之间的区别吗 还应该针对哪些请求使用哪一个 我一直在使用 facebook python SDK 来创建广告 但我时不时会遇到速率限制 但在我的营销 API 仪表板中我没有
  • 如何为 eclipse 和 android studio 提供单一的 android SDK 和 AVD

    我是 Eclipse 用户 并在其上轻松开发了 Android 应用程序 但最近 当我看到 android studio 出现并由 android 网站提供时 我想尝试一下 因为它看起来非常有前途 我已经在我的 D 盘中下载了 androi
  • 减少 CosmosDB 的预配置吞吐量

    我有一个 cosmos DB 它在数据库级别配置了 4 个容器和 400 个 RU 我添加了 2 个容器 并且在没有警告的情况下 配置的 RU 增加到了 600 个 下面的文档解释了为什么会发生这种情况 第 4 个以上的每个容器至少需要额外
  • 使用多维 std::initializer_list

    我有一个关于在 C 中使用多维 std intializer list 的问题 我有一个 Matrix 类 我希望能够像这样初始化它 Matrix
  • 通过构建所有 asset_path 值来避免 *.js.erb 文件

    因此 我想避免使用 ERB 处理 JavaScript 文件 这样我就可以获得正确的资源路径 例如图像 目前 这似乎是流行的方法 var myImage 当然 这需要将文件名更改为 erb 以便对其进行处理 我宁愿将 ERB 的丑陋隔离到项
  • rand() 在 C 语言中有多独特?

    我在用rand 对于需要唯一值的 6 位字段 我做对了吗 几率有多大 rand 可以在连续或频繁的通话中给我类似的值吗 当我使用 rand 时 它是独一无二的 但是 当我打电话时返回相同的号码srand time NULL or srand
  • Powershell脚本:无法读取执行程序的返回值

    我正在使用 PowerShell 运行一个执行的脚本wget获取网页 一个简单的数据库导入脚本 并分析其输出 错误消息或 确定 我正在使用答案中的代码上一个问题 https stackoverflow com questions 20345
  • 最新的浏览器中有内置的 javascript 字符串哈希函数吗?

    每当新版本的浏览器出现时 我都会听到添加新的东西 比如 webGL 和其他没有人真正知道它们是否能赶上的技术 但我想知道是否有人考虑过 JS 中的哈希函数 MD5 SHA1 等 等基本内容 我所说的最新浏览器也指当今的开发版本 例如 Ope
  • 如何使用 EF 6.0 中的代码优先方法从 sql 表中删除列?

    我错误地在数据库中添加了一列 名为doj现在 如果我想使用代码优先方法从表中删除该列 我应该做什么 我已经尝试过这些事情 1 从模型中删除列定义 2 删除了迁移历史记录 3 添加迁移4 更新数据库 但它仍然没有反映在数据库中 我哪里犯了错误
  • 在 Spark 中,广播是如何工作的?

    这是一个非常简单的问题 在 Spark 中 broadcast可用于有效地将变量发送给执行器 这是如何运作的 更确切地说 何时发送值 我一打电话就发送broadcast 或者何时使用这些值 数据到底发送到哪里 发送给所有执行者 还是只发送给
  • 将数字列表转换为范围

    我有一堆数字 请说以下内容 1 2 3 4 6 7 8 20 24 28 32 那里提供的信息可以用 Python 表示为范围 range 1 5 range 6 9 range 20 33 4 在我的输出中我会写1 4 6 8 20 32
  • Swing 应用程序 -> 拖放到桌面/文件夹

    当 Mac 的 Finder Windows 的 Explorer 将 Swing 应用程序中的特定项目拖放到桌面和文件夹时 如何获取我放弃的前路径 我很高兴教给我必要的课程和方法 这是一个小程序 但它适用于任何框架或窗口 public c
  • 根据内容拆分 .txt 文件

    我有一个巨大的 txt文件如下 small file content 1 br small file content 2 br small file content n br 我如何将其分割成n个文件 最好通过bash Use csplit
  • 将 models.py 拆分为多个文件

    我正在尝试拆分models py我的应用程序分成几个文件 我的第一个猜测是这样做 myproject settings py manage py urls py init py app1 views py init py models in
  • 如何声明两个列表具有相同的长度?

    我需要知道如何比较 Prolog 中两个列表的长度 这是我到目前为止所拥有的 sum N1 N2 checklength N1 N2 checklength N1 N2 L1 is length N1 What L2 is length N
  • 如何使用 selenium ide 专注于新窗口?

    我正在尝试使用 selenium ide 来复制操作 该操作是单击打开新窗口的链接 如何让 selenium ide 聚焦在新窗口而不是另一个窗口上 它对我不起作用 选择窗口 为此 您需要使用selectWindow windowName命
  • 创建 JSON 并编辑复杂查询 (oracle 11g)

    我有 4 个不同的表 table price product 包含与产品相关的信息和 他们的价格 table price list 包含与价目表相关的信息 prices per client 包含与价格相关的信息 不同的客户给出特定的产品
  • 角度范围绑定 &(&) 是一次性绑定吗?

    角度范围绑定 是一次性绑定吗 我看到它被称为单向绑定 但它也是一次性的吗 假设我有
  • 在 Java 中嵌入树状图

    我正在寻找一个能够绘图的图书馆树状图 http en wikipedia org wiki DendrogramJava中的数据 不计算它们 我可以自己做 你有任何线索吗 已经尝试通过谷歌搜索它 但没有找到任何不独立的东西 虽然我需要将生成
  • 使用 Java Graphics2D API 在 TextLayout 中将文本右对齐

    因此 我正在使用 Java 教程中的代码来绘制一段文本 但我不知道如何将文本与右边距对齐 我刚刚包括attstring addAttribute TextAttribute RUN DIRECTION TextAttribute RUN D