Bonjour,
I'm trying my hand at animation, and have found myself a strip of explosions on a single image in a row. I want them to show one after the other in sequence to animate an explosion. Naturally, I'm thinking ImageIcon
on JLabel
, but when I looked at the JLabel
spec I found this line:
JLabel(Icon icon)
-- Creates a JLabel
instance with the specified image. The label is centered vertically and horizontally in its display area.
I want to be able to show only part of a full image in the label, then load another part of it: basically loading the different stages on the one image.
Is there a way to do this without cutting up the image and loading each one individually?
You could load the image initially using a BufferedImage
, whereby you could call getSubimage
to obtain a cropped copy of the Image
while retaining the original Image
You could also paint the image using this drawImage
method from the Graphics
class to crop the image being drawn
public abstract boolean drawImage(Image img,
int dx1,
int dy1,
int dx2,
int dy2,
int sx1,
int sy1,
int sx2,
int sy2,
ImageObserver observer)
Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit inside the specified area of the destination drawable surface. Transparent pixels do not affect whatever pixels are already there.
Parameters:
- img - the specified image to be drawn. This method does nothing if img is null.
- dx1 - the x coordinate of the first corner of the destination rectangle.
- dy1 - the y coordinate of the first corner of the destination rectangle.
- dx2 - the x coordinate of the second corner of the destination rectangle.
- dy2 - the y coordinate of the second corner of the destination rectangle.
- sx1 - the x coordinate of the first corner of the source rectangle.
- sy1 - the y coordinate of the first corner of the source rectangle.
- sx2 - the x coordinate of the second corner of the source rectangle.
- sy2 - the y coordinate of the second corner of the source rectangle.
- observer - object to be notified as more of the image is scaled and converted.
See an example here that uses a single animation sprite to choose different location of the image to draw.
Prior to 20JAN15, the sample program pointed to from this answer (which was used to create the animated display of the explosion above) had logic errors and only showed 2 rows of images. (Note that the example doesn't show the last row of the explosion...)
Please see the additional answer on the pointed to-page which contains fixes to the program. Cheers. Warren K.