How does Java Graphics.drawImage() work and what is the role of ImageObserver
Asked Answered
M

4

21

How should Java's drawImage() be used? I do not find the JDK documentation very forthcoming. For example all drawImage signatures require an ImageObserver but the documentation for this is not very helpful for new users.

Melodramatize answered 5/11, 2009 at 23:36 Comment(0)
E
31

You can get away with Graphics.drawImage(img, x, y, null) [or similar]. The ImageObserver parameter is a callback to inform you of the progress of the draw operation; and is really only useful if you're fetching the Image parameter asynchronously.

To be clearer, if you call drawImage with an incompletely loaded Image it will:

  1. return false (immediately)
  2. draw as much of the Image as possible (all that is loaded)
  3. and, at some future point, call into the ImageObserver when more of the Image is available

Basically, if you're working with in memory Images (either loaded from the file system, or constructed by your program) don't worry about the ImageObserver parameter. If you're loading Images across the network and not explicitly waiting for them to load, you'll need to employ an ImageObserver to make sure "completely" draw an Image.

Emergence answered 5/11, 2009 at 23:48 Comment(0)
C
8

Image objects aren't necessarily completely loaded. If Graphics.drawImage is invoked on an incomplete image it will draw as much of the image as it can, and then alert the ImageObserver (by calling imageUpdate) when more of the image is loaded.

The ImageObserver can be null, in which case you won't get any notification. This is common if the images are known to be loaded, or if there's already another mechanism doing repaints.

Note that Component implements ImageObserver, and its imageUpdate method will cause a repaint on the affected area.

Canebrake answered 5/11, 2009 at 23:55 Comment(1)
imageUpdate is also called for animated images.Costanzia
T
1

Actually I used drawImage() many times always with ImageObserver parameter set to null. Ok that doesn't mean it's useless, but I did whatever I needed without knowing its use..

Tripoli answered 5/11, 2009 at 23:45 Comment(1)
:-) so did I - and I had no idea whether it would be a problem.Melodramatize
D
1

As others have intimated, this API was conceived when it was assumed that the images that would be rendered would be being loaded over the network. When you ask the toolkit to load an image, the assumption is that it is just a shell, and that the bytes required to know its size and pixels are still crawling down the wire.

In this case drawImage may render nothing when it is first called. As the size and pixels become available, the ImageObserver is notified. In the case of Component implements ImageObserver, its behaviour is to repaint when the data is available.

Dodecanese answered 6/11, 2009 at 0:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.