【问题标题】:Image not scaling with Graphics.drawImage()图像不使用 Graphics.drawImage() 缩放
【发布时间】:2014-11-13 04:35:23
【问题描述】:

我正在创建一个 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);,但它不起作用。

【问题讨论】:

  • dbi 是空的,还是从 getGraphics() 调用中抛出 NullPointerException?在这里发布几行堆栈跟踪会有所帮助。
  • @Galen Nare 为什么不使用 Image 类的 getScaledInstance(width, height, hint) 方法来缩放图像??
  • @Muhammad:引用了一些危险here
  • @trashgod 我对你的两个答案都投了票,因为它值得:)
  • @Muhammad 因为它会导致 ClassCastException,因为 ToolkitImage 正在某处使用,我不知道在哪里。我从不创建 ToolkitImage...

标签: java image swing graphics


【解决方案1】:

此时框架在您的程序中不可见; getGraphics() 无效。而是使用BufferedImage#createGraphics(),如here 所示。也可以考虑AffineTransformOp,见here

【讨论】:

    【解决方案2】:

    我找到了对我自己的问题有效的答案。

    int imageWidth  = source.getWidth();
            int imageHeight = source.getHeight();
    
            double scaleX = (double)width/imageWidth;
            double scaleY = (double)height/imageHeight;
            AffineTransform scaleTransform = AffineTransform.getScaleInstance(scaleX, scaleY);
            AffineTransformOp bilinearScaleOp = new AffineTransformOp(scaleTransform, AffineTransformOp.TYPE_BILINEAR);
    
            source = bilinearScaleOp.filter(
                source,
                new BufferedImage(width, height, source.getType()));
    

    我在几年前的另一个问题上发现了它。

    How to improve the performance of g.drawImage() method for resizing images

    【讨论】:

      猜你喜欢
      • 2011-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-25
      • 2013-01-05
      • 1970-01-01
      • 1970-01-01
      • 2013-12-07
      相关资源
      最近更新 更多