0

我想在图像(BufferedImage)上写一些文本,但是当文本更新时,新文本会覆盖旧文本,例如所有数字都写在同一个地方,有人可以帮忙。我正在使用这段代码:

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;

public class Prove extends JPanel {
    int size =  800;
    private BufferedImage sc ;
    JLabel label ;
    private int counter =0 ;

    public Prove()
    {       
        JFrame frame = new JFrame();
        frame.getContentPane().add(this);
        frame.setSize(2*size, size);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        try{ sc = ImageIO.read(new File("Images/ser.jpg"));     
            label =new JLabel(new ImageIcon(sc));
            this.add(label);
        }catch(IOException e){}


    }

    public void paintComponent(Graphics g)
    {
        g.setColor(Color.GRAY);
        g.fillRect(0,0, getWidth(),getHeight());        //prapavijen 

        Graphics2D g2 = (Graphics2D)g;

        paintScore(g2);
    }

    public void paintScore(Graphics g2)
    {

        if(sc != null)
        {
            Graphics gi = sc.createGraphics();
            gi.setFont(new Font("Times New Roman", Font.BOLD, 20));
            String r = counter+"";
            gi.drawString(r, 20, 20);
            counter ++;
            this.repaint();
            try{Thread.sleep(500);}
            catch(InterruptedException e){}
            System.out.println(counter);
        }   

    }

    public static void main(String[] args)
    {
        new Prove();

    }



}
4

3 回答 3

1

您正在将文本绘制到相同的位置,它必然会覆盖

gi.drawString(r, 20, 20);

如果您希望新文本出现在旧文本下方,则需要更改垂直坐标

于 2012-04-30T11:54:43.023 回答
1

您必须保留原始图像的未修改副本。试试这个伪代码:

BufferedImage img1 = loadImage();

在你的油漆代码中:

BufferedImage img2 = createEmptyImage( img1 ); // same size, mode and depth
Graphics g = img2.getGraphics();
try {
    g.draw( img1 ); // background
    g.drawString(); // render text on top of it
} finally {
    g.dispose();
}
于 2012-04-30T12:43:43.343 回答
1

没有理由直接在图像上绘制文本。只需将图像绘制到组件Graphics实例,然后将字符串绘制到相同的Graphics.

于 2012-05-02T17:45:13.463 回答