简体   繁体   English

用java在图像上绘制文本

[英]Draw a text on a image in java

I am trying t draw different things over an image, in the first case works well, but I don t know how to deal with the second case: first case:我试图在图像上绘制不同的东西,在第一种情况下效果很好,但我不知道如何处理第二种情况:第一种情况: 在此处输入图片说明 second case:第二种情况: 在此处输入图片说明

As you can see the path is larger.如您所见,路径更大。 This is the code for drawing text:这是绘制文本的代码:

public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g = g.create();
        g.setColor(Color.WHITE);
        g.setFont(getFont().deriveFont(24f));
        g.fillRect(0, 0, getWidth(), getHeight());

        int margin = 1;

        g.drawImage( this.image, margin, margin, this.image.getWidth(), this.image.getHeight(), this);
        g.setColor(Color.RED);
        int i=0;

       if(name1!=null) {
            g.drawString(name1, 50, 50);
            if(i==0) {
                i = i + 40;
            }
        }
        if(path!=null) {
            g.drawString(path, 40, 50 + i);

                i = i + 40;

            }
        if(size!=null){
            g.drawString(size,50,50+i);
                i = i + 40;

        }
        if(dimention!=null){
            g.drawString(dimention,50,50+i);
                i = i + 40;
        }
        if(date!=null){
            g.drawString(date, 50,50+i);

        }
    }

If you want to use AWT only, then use Graphics.getFontMetrics (optionally specifying the font if it is not a standard font) to get a FontMetrics, and then FontMetrics.stringWidth to get the width for the specified string.如果您只想使用 AWT,则使用 Graphics.getFontMetrics(如果不是标准字体,可选择指定字体)获取 FontMetrics,然后使用 FontMetrics.stringWidth 获取指定字符串的宽度。

For example, if you have a graphics variable named g, use:例如,如果您有一个名为 g 的图形变量,请使用:

int width = g.getFontMetrics().stringWidth(text);

You have to calculate how big the string is to cut it off at the appropriate place.您必须计算绳子有多大才能在适当的位置将其切断。

String myText = "mylongtempstringformeasuring"; // The string to check.
int maxWidth = 1000; // The width of the image.
String tempString = myText;
int i = 0;
while (g.getFontMetrics().stringWidth(tempString) >= maxWidth) {
  i++;
  tempString = tempString.substring(0, tempString.length() - i);
}

String remainText = tempString.substring(tempString.length() - 1, myText.length() - 1);

After that you know after how many characters (variable i) you have to truncate the string.之后,您知道在多少个字符(变量 i)之后您必须截断字符串。 After that you can do the same for the remain of the text.之后,您可以对文本的其余部分执行相同的操作。 It's best to do the whole thing in a loop, too.最好在循环中完成整个事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM