Loading only part of an image

Started by
3 comments, last by Matthewj234 12 years, 3 months ago

Block = getImage(this.getClass().getResource("/Sprites/maptiles.png"));


Is the code I use to load an image. Is there a way to only load a portion of the png file to Block. Trying to take a tile set and put it into an array without splitting the image physically and loading it that way.

Thanks.

I was trying to use a bufferedImage but couldn't figure out how to draw that buffered image to the "screen"
tried

g.drawImage(Block, 0, 0, this);

and tried

Graphics2D g2 = (Graphics2D)g;
g2.drawImage(Block, 0, 0, this);


and google is failing me today.

Sprite Creator 3 VX & XP

WARNING: I edit my posts constantly.

Advertisement
Take a look at the JavaDoc of drawImage(). You can specify the source rectangle to draw. So, no need to split up while loading.
So rather than drawing the image like

public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
g2.drawImage(Block, 0, 0, this);
}


I would

public void paint(Graphics g)
{
g.drawImage(Block, 0, 0, 32, 32, 64, 64, 96, 96, this);
}


to draw the part of the image from 64, 64, 96, 96 to 0, 0, 32, 32 ? nice. I didn't see that there were more than one form of drawImage. You sir rock that worked.

Am I able to take those sections of the image and put them into another image or do I have to use a BufferedImage? And if I have to use BufferedImage how would I draw that BufferedImage. I would like to put the smaller images into an array. or should I just create a loop for the drawing of each tile and it's location rather than putting the tileset image into an array?

Sprite Creator 3 VX & XP

WARNING: I edit my posts constantly.


Am I able to take those sections of the image and put them into another image or do I have to use a BufferedImage? And if I have to use BufferedImage how would I draw that BufferedImage. I would like to put the smaller images into an array.

You could do that, but is there any specific reason for that approach ?
I keep all tiles in one image and only put the image rectangles in separate tile objects.
Also take a look at VolatileImage to benefit from hardware support.

To create new empty images:
GraphicsConfiguration#createCompatibleImage()
GraphicsConfiguration#createCompatibleVolatileImage()
There's another way. If you are thinking of a spritesheet, which i believe you are, use BufferedImages.

E.g.

BufferedImage sheet = ImageIO.read(Class.class.getResource(url));

bufferedImage tile = grabTile(sheet, xpos, ypos, width, height);

public bufferedImage grabTile(BufferedImage sheet, int xpos, int ypos, int width, int height){
return sheet.grabSubImage(xpos, ypos, width, height);
}


I believe the above is correct, currently i am unable to see an IDE to check.

- Numprt

This topic is closed to new replies.

Advertisement