我正在创建一个 2D 平台游戏,并尝试使用我创建的自定义库来缩放图像。该代码在调用 dbi.getGraphics() 时给出 NullPointerException。
public void scale(int width, int height) {
JFrame tempFrame = new JFrame();
tempFrame.setSize(source.getWidth(null), source.getHeight(null));
Image dbi = tempFrame.createImage(source.getWidth(null), source.getHeight(null));
Graphics dbg = dbi.getGraphics(); // NullPointerException
dbg.drawImage(source, 0, 0, width, height, null);
source = dbi;
//BufferedImage temp = (BufferedImage) source;
//temp.getScaledInstance(width, height, Image.SCALE_DEFAULT);
//source = temp;
}
我正在使用 dbi.drawImage() 来缩放图像。我尝试过 source.getGraphics().drawImage(source,0,0,width,height,null);
,但它不起作用。
最佳答案
此时该框架在您的程序中尚未可见; getGraphics()
无效。而是使用 BufferedImage#createGraphics()
,如图here 。另请考虑 AffineTransformOp,参见 here .
关于java - 图像未使用 Graphics.drawImage() 缩放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26887758/