开发者

getSize(), getWidth(), getHeight() returns -1

I have an Image img that, when trying to use any of above mentioned get methods, returns -1. W开发者_运维知识库hy is this? And what is an ImageObserver object?


According to the documentation for Image, these methods return a -1 if the size, width, or height (respectively) are not yet known.

Also, ImageObserver is simply an interface that provides methods to get notifications about the information of an Image object that is being constructed.


You can use the MediaTrack to get your image's width & height like that :

 // ...

 Image img;
 // ...
 // ...  loading the image using IO or Toolkit ot something

 MediaTracker MTrack = new MediaTracker(this); // in my case, 'this' is a JFrame

 MTrack.addImage(img,1);
 try 
{
    MTrack.waitForID(1);
} 
catch(InterruptedException e) 
{
   e.getMessage();
}

int width = img.getWidth(null);
int height = img.getHeight(null);

double ratio = (double)width/(double)height;

// ....
// ....


According to the Java docs, it seems that if you call getHeight() etc. on an Image while it's still in the construction phase, such that the height is not really "known", -1 is returned and the ImageObserver provided is notified.

ImageObserver is an interface that provides a way for you to have a callback method that is called when the image is updated in some way. ImageObserver is implemented by java.awt.Component, so if you extend that in the containing class you could override imageUpdated() and store the image height when the function is called asynchronously (if Image.getHeight returns -1).


In GraphTest, override imageUpdate:

@Override
public void imageUpdate(Image img, int flags,
               int x, int y, int width, int height) {
    if ((flags & (WIDTH|HEIGHT)) == (WIDTH|HEIGHT)) {
        // width and height have meaningful values, do your resize here
    }
    super.imageUpdate(img, flags, x, y, width, height);
}


The problem is the time needed to load the Image.

As long as the image is not loaded you get the -1. When the image is finally loaded, it fires the ImageObserver. The obeserver, in your case the Background instance - g.drawImage(bkg, 0, 0, this); - will force a repaint of the Background causing the now loaded image to be painted.

You can also use the java.awt.MediaTracker to track the status of your Image.

[]]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜