sparklyllama
sparklyllama

Reputation: 1326

paintComponent(g) Not Scaling BufferedImage?

In my main class for my Game, I have the following code:

// 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);

}

The image isn't being scaled though, it's drawn at it's actual dimensions, rather than having it's dimensions multiplied by 3 (SCALE).

Also, if I remove the super.paintComponent(g); line and the g.drawImage(...); line, the rectangle is still being rendered.

Thanks!

Upvotes: 0

Views: 277

Answers (2)

Martin Frank
Martin Frank

Reputation: 3474

use the scaling method to draw a scaled instance of your image:

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

as seen on 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 gave me also some interesting hint: https://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html - have a look at this!

Upvotes: 2

ortis
ortis

Reputation: 2223

If you want the image to fit the entire Jpanel, you should use the following:

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);

}

This will make your image to be scaled to the whole Jpanel. Of course, you will not see the rectangle because the image will be drawn over it.
Also, be sure to actually put something in your image.

Upvotes: 1

Related Questions