Working with Graphics |
Here is a code example that displays an image at its normal size in the upper left corner of the Component area (0, 0):Here is a code example that displays an image scaled to be 400 pixels wide and 68 pixels tall, starting at the coordinates (125, 0):g.drawImage(image, 0, 0, this);Below is an applet that loads a single image and displays it twice, using both code examples that you see above. Here is the full code for the program (which can function both as an applet and as an application).g.drawImage(myImage, 125, 0, 400, 68, this);
The Graphics class declares the following
drawImage()
methods. They all return a boolean value, although this value is rarely used. The return value istrue
if the image has been completely loaded [and thus completely drawn?]; otherwise, it'sfalse
[CHECK].The
public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer)
public abstract boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer)
public abstract boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer)
public abstract boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer)
drawImage()
methods have the following arguments:The reason why
Image img
- The image to draw.
int x, int y
- The coordinates of the upper left corner of the image.
int width, int height
- The width and height (in pixels) of the image.
Color bgcolor
- The color to draw underneath the image. This can be useful if the image contains transparent pixels.
ImageObserver observer
- An object that implements the ImageObserver interface. This object will be notified whenever new information about the image becomes available. Most programs can simply specify
this
.this
works as the image observer is that the Component class implements the ImageObserver interface. Its implementation invokes therepaint()
method as the image data is loaded, which is usually what you want to happen.The
drawImage()
returns immediately [after displaying the image?], even if the image data hasn't been fully loaded (and thus might be displayed only partially). If you want to make sure thatdrawImage()
draws only complete images, then you must track image loading. As the previous page explains, you can track image loading either by implementing ImageObserver in your Component or by using the MediaTracker class. An example of using MediaTracker is in Improving the Appearance and Performance of Image Animation.
Working with Graphics |