简体   繁体   中英

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.

For example, if you have a graphics variable named g, use:

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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