【问题标题】:paintComponent(g) Not Scaling BufferedImage?paintComponent(g) 不缩放 BufferedImage?
【发布时间】:2014-08-12 09:48:42
【问题描述】:

在我的游戏主类中,我有以下代码:

// dimensions
public static final int WIDTH = 266;
public static final int HEIGHT = 200;
public static final int SCALE = 3;

// game loop
private Thread thread;
private boolean running = true;
public static int count = 0;

// rendering
private BufferedImage image;

public Panel() {

    setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));

    image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB);

}

public void run() {

    long start = System.nanoTime();
    final double numUpdates = 30.0;
    double ns = 1000000000 / numUpdates;
    double delta = 0;

    while(running) {

        long current = System.nanoTime();
        delta += (current - start) / ns;
        start = current;
        if(delta >= 1) {
            update();
            delta--;
        }
        repaint();

    }

}

public void paintComponent(Graphics g) {

    super.paintComponent(g);

    g.setColor(new Color(230, 100, 100));
    g.fillRect(0, 0, 200, 100);

    g.drawImage(image, 0, 0, WIDTH * SCALE, HEIGHT * SCALE, null);

}

public static void main(String[] args) {

    JFrame frame = new JFrame("Rage Mage");

    frame.add(new Panel());
    frame.setResizable(false);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

image 并没有被缩放,它是按照实际尺寸绘制的,而不是让它的尺寸乘以 3 (SCALE)。

此外,如果我删除 super.paintComponent(g); 行和 g.drawImage(...); 行,矩形仍在渲染中。

谢谢!

【问题讨论】:

  • 你认为drawImage()为什么会缩放图像?您正在调用的方法的 Javadoc 的第一行声明:“绘制尽可能多的指定图像已经缩放以适合指定的矩形。”。您需要事先进行实际缩放,例如,使用图像的getScaledInstance 方法。
  • @Ordous 我现在读了它,是的,这就是解决方案! - 但不要使用 Image.getScaledInstance!

标签: java bufferedimage scaling


【解决方案1】:

使用缩放方法绘制图像的缩放实例:

Graphics gr; 
gr.drawImage(0,0,WIDTH*SCALE,HEIGHT*SCALE,0,0,WIDTH,HEIGHT,null);

http://docs.oracle.com/javase/7/docs/api/java/awt/Graphics.html#drawImage%28java.awt.Image,%20int,%20int,%20int,%20int,%20java.awt.image.ImageObserver%29所见

@MadProgrammer 还给了我一些有趣的提示:https://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html - 看看这个!

【讨论】:

  • 啊,感谢getScaledInstance 的提示,我遇到了一些问题,但还不足以对替代品进行任何实际研究。
  • 不要对我说谢谢 - 感谢 MadProgrammer,他写了关于那个...
【解决方案2】:

如果您希望图像适合整个 Jpanel,您应该使用以下内容:

public void paintComponent(Graphics g)
{

    super.paintComponent(g);

    g.setColor(new Color(230, 100, 100));
    g.fillRect(0, 0, 200, 100);
    g.drawImage(image, 0, 0, getWidth(), getHeight(), null);

}

这将使您的图像缩放到整个 Jpanel。当然,您不会看到矩形,因为图像将被绘制在它上面。
另外,一定要在你的图片中实际放置一些东西。

【讨论】:

    猜你喜欢
    • 2012-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多