java - 在 PaintedImage Java 上绘制字符串

标签 java swing paintcomponent drawimage drawstring

我需要在绘制的图像上绘制字符串。我正在进行的项目还要求字符串每秒至少在屏幕上移动 22 次。因此,它的位置可以是图像上的任何位置。因此,重新绘制带有字符串的图像是不可能的,因为我觉得有更好的方法可以做到这一点,并且这会不必要地消耗重新绘制整个图像的资源。我也尝试过使用 panel.getGraphics 然后在图像上绘画,但所有绘制的文本都在屏幕上(代码如下)。我想知道是否有人可以指导我如何在 PaintImage 上绘制文本的正确方向,但它也需要在需要时重置其位置。我尝试过的不会重置其先前位置的代码如下。

带有图像的原始面板:

public class PanelForImages extends JPanel{

private BufferedImage image;

public PanelForImages(File image) throws IOException{
    //this.image = image;
    //URL resource = getClass().getResource("so2.jpg");
    this.image = ImageIO.read(image);

}

 @Override
 public void paintComponent(Graphics g){
    //super.paint(g);
    //super.paintComponents(g);
    super.paintComponent(g);
    //g.drawImage(image, 3, 4, this);
    g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
    g.drawString("HELLOOOOOOOOOOOOOOOOOOOOOOOO", 400, 400);
    //repaint();

 }
}

我尝试在图像上绘制字符串的方法。

public void drawFixationsOnFrame(GazeData gazeData){

    Graphics g = this.panelForImages.getGraphics();


    g.drawString("TEsting 123", (int)gazeData.smoothedCoordinates.x, (int)gazeData.smoothedCoordinates.y);

    g.dispose();

    jF.revalidate();
}

我还尝试过制作一个新面板,然后将其添加到当前面板中,但似乎不起作用。我不知道如何才能使它位于 panelForImages 的顶部而不隐藏 panelForImages。

最佳答案

The project I am working on also requires the string to move around the screen at least 22 times in a second. Hence, its position can be anywhere on the image. So, redrawing the image with the string on it won't be possible as I feel there are better ways of doing this and that would unnecessarily consume resources redrawing the whole image.

然后不要重绘整个图像。 JComponent repaint(...) 方法有一个重写,它允许您仅重新绘制选定的矩形(请查看 JComponent API 了解更多信息)。您将需要在 Swing Timer 中移动图像,然后重新绘制其旧位置(以摆脱旧的字符串图像)并重新绘制其新位置。如果您需要字符串的尺寸,请使用 FontMetrics 来帮助您获取其边界矩形。

我注意到您的代码还有两个令人担忧的问题,其中一些被注释掉了:

  • 在组件上调用 getGraphics() 来获取其图形组件并用它进行绘制 - 您不希望这样做,因为这会导致 Graphics 对象存在短暂的风险损坏的图像或 NPE
  • paintComponent 中调用 repaint()。这是一种糟糕且完全不受控制的动画制作方式。相反,请使用 Swing Timer,这样您就可以完全控制动画,并且不会将 PaintComponent 用于不该用于的用途。

关于java - 在 PaintedImage Java 上绘制字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41567671/

相关文章:

java - 在Java中,如何将每个字符设置为整数?

java - 包含 JPanel 的 JScrollPane 不会滚动

java - 如何更改禁用的 jbutton 的颜色?

java - 填充矩形图形错误

Java:将一维数组映射到位图

java - 制作无边框 JFrame

java - 如何修复 "android.view.InflateException: Binary XML file line #23: Binary XML file line #23: Error inflating class fragment"

java - JList - 关于 toString() 演示的设计问题

java - 鼠标定位和图形绘制

java - PaintComponent 自己进行绘画