【问题标题】:How to Add Height element while Appending text on images如何在图像上附加文本时添加高度元素
【发布时间】:2012-12-08 22:59:28
【问题描述】:

我正在寻找是否可以在给定的Example 中添加高度元素。

这样我就可以指定

public void drawString(Graphics g, String s, int x, int y, int width,int height)

现在,如果我的文字超过高度,它将与下一个文字重叠。

【问题讨论】:

  • 你想做什么?
  • 你想绘制超过一行的字符串..?
  • 我正在绘制超过一行的字符串。但是如果最后一行超过指定的高度,我想限制字符串。
  • 一种方法是在 JLabel 中使用 HTML 格式并将所需的宽度设置为样式。有关示例,请参阅 LabelRenderTest 源。一旦设置了宽度和字符串,标签应该能够报告首选尺寸(包括高度)。

标签: java image text graphics awt


【解决方案1】:

我没有对此进行测试,但这可能会帮助您解决问题..

public void drawString(Graphics g, String s, int x, int y, int width, int height) {
    // FontMetrics gives us information about the width,
    // height, etc. of the current Graphics object's Font.
    FontMetrics fm = g.getFontMetrics();

    int lineHeight = fm.getHeight();

    int curX = x;
    int curY = y;
    int totalHeight = 0;

    String[] words = s.split(" ");

    String word = "";
    // end of words array wasn't reached and still some space left
    for(int i = 0; i < words.length && totalHeight <= height; i++) {

        // Find out thw width of the word.
        int wordWidth = fm.stringWidth(word + " ");

        // If text exceeds the width, then move to next line.
        if (curX + wordWidth >= x + width) {
            curY += lineHeight;
            totalHeight += lineHeight;
            curX = x;
        }

        g.drawString(word, curX, curY);

        // Move over to the right for next word.
        curX += wordWidth;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-04
    • 2012-01-03
    • 1970-01-01
    • 2013-05-06
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多