简体   繁体   English

用Java在图像上绘制字符串

[英]Draw string to image in Java

I need to draw a string to a BufferedImage in Java. 我需要在Java中绘制一个字符串到BufferedImage。 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. 我需要创建一个仅包含字符串的新BufferedImage。 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. 字符串上方和字符串右侧的多余空间是可以容忍的,但是在绘制字符串的下方和左侧我都没有多余的空间。

图片

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. 任何帮助,将不胜感激。

You can use Graphics2D#drawString method: 您可以使用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); 
  }
}

I need to draw a string to an image in Java. 我需要在Java中为图像绘制字符串。 I have tried to do it myself, but I always end up having extra space 我自己尝试过做,但是我总是最终有多余的空间

I can't tell if you are trying to create an image of a String or add some text to an existing image. 我不知道您是要创建String的图像还是在现有图像中添加一些文本。 Since you say you have extra space I assume you are trying to create an image of the text and you don't know how big to make the BufferedImage that you are drawing on. 因为您说您有多余的空间,所以我假设您正在尝试创建文本的图像,并且您不知道要制作多大的BufferedImage。

Create a JLabel with the text you want. 用所需的文本创建一个JLabel。 Then you can use the Screen Image class to create an image of the label component. 然后,您可以使用Screen Image类创建标签组件的图像。 The the image will be the exact size pf the text. 图像将是文本的确切大小。

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

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