1

I need to draw a string to a BufferedImage in Java. The way this is done doesn't matter, however the image should take up only the space it needs, like in the example below. I need a new BufferedImage created containing only the string. Extra space above the string and on the right side of the string could be tolerated, but I can't have extra space below and left of the drawn string.

Image

Is something like this possible? I have tried to do it myself, but I always end up having extra space which is not what I want. Any help would be appreciated.

4

2 回答 2

2

您可以使用Graphics2D#drawString方法:

import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import javax.swing.JComponent;
import javax.swing.JFrame;

public class MainClass{
  public static void main(String[] args) {
    JFrame jf = new JFrame("Demo");
    Container cp = jf.getContentPane();
    MyCanvas tl = new MyCanvas();
    cp.add(tl);
    jf.setSize(300, 200);
    jf.setVisible(true);
  }
}

class MyCanvas extends JComponent {
  public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D)g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
    Font font = new Font("Serif", Font.PLAIN, 96);
    g2.setFont(font);

    g2.drawString("Test string", 40, 120); 
  }
}
于 2013-06-24T22:15:50.393 回答
-2

我需要在 Java 中为图像绘制一个字符串。我试过自己做,但我总是有额外的空间

我不知道您是在尝试创建字符串的图像还是在现有图像中添加一些文本。既然您说您有额外的空间,我假设您正在尝试创建文本的图像,并且您不知道要绘制的 BufferedImage 有多大。

使用您想要的文本创建一个 JLabel。然后您可以使用Screen Image类来创建标签组件的图像。图像将是文本的确切大小。

于 2013-06-24T22:16:14.723 回答