views:

897

answers:

3

Changing the size of an Image Widget in GWT changes the size of the image element, but does not rescale the image on the screen. Therefore, the following will not work:

Image image = new Image(myImageResource);
image.setHeight(newHeight);
image.setWidth(newWidth);
image.setPixelSize(newWidth, newHeight);

This is because GWT implements its Image widget by setting the background-image of the HTML <img... /> element as the image, using CSS.

How does one get the actual image to resize?

+3  A: 

I saw this blog entry, which solves the problem by using a GWT DataResource instead of ImageResource. It turns out that the same technique will actually work with ImageResource, if you use it as follows:

Image image = new Image(myImageResource.getURL());
image.setPixelSize(getLength(), getHeight());
Daniel
This will resize the image but will not maintain its aspect ratio.
adranale
+1  A: 

Try the image loader widget http://code.google.com/p/gwt-image-loader The FitImage class provides what you are looking for.

PS: apply also patches from issues, as there are some minor bugs which I have fixed

Drejc
A: 

my final solution was to add a load handler on the image to resize it according to the dimensions of the loaded image (i.e. respectnig the ratio).

image.addLoadHandler(new LoadHandler() {
        @Override
        public void onLoad(LoadEvent event) {
            Element element = event.getRelativeElement();
            if (element == image.getElement()) {
                int originalHeight = image.getOffsetHeight();
                int originalWidth = image.getOffsetWidth();
                if (originalHeight > originalWidth) {
                    image.setHeight(MAX_IMAGE_HEIGHT + "px");
                } else {
                    image.setWidth(MAX_IMAGE_WIDTH + "px");
                }
            }
        }
    });

where MAX_IMAGE_WIDTH and MAX_IMAGE_HEIGHT are constants that determine the maximum allowed size of the image.

adranale