Graphics.drawImage()不是绘制图像

时间:2017-04-04 06:08:30

标签: java

    Image img = null;
    try {
        img = ImageIO.read(new File("pig.png"));
    } catch (IOException e){

    }
    Graphics g = img.getGraphics();
    g.drawImage(img, 0, 0, null);

我使用本教程: https://docs.oracle.com/javase/tutorial/2d/images/

程序运行,但图像无法显示。

2 个答案:

答案 0 :(得分:1)

您必须使用GUI组件

你可以简单地使用Swing,

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;

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

class DemoPaint extends JComponent {

  public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;

    Image picture = Toolkit.getDefaultToolkit().getImage("yourFile.gif");
    g2.drawImage(picture, 10, 10, this);
    g2.finalize();
  }
}

public class DrawImageGraphics {
  public static void main(String[] a) {
    JFrame window = new JFrame();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setBounds(30, 30, 300, 300);
    window.getContentPane().add(new DemoPaint());
    window.setVisible(true);
  }
}

我希望这会有所帮助。

答案 1 :(得分:0)

将图片加载到Image对象后,创建一个透明的缓冲图像

BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);

将图像绘制到缓冲图像

Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(img, 0, 0, null);
bGr.dispose();