我编写了一个接受 ImageResource 对象的类,您可以设置所需的图像像素大小。它使用 CSS background-Position 和 CSS background-size 来达到目的:
ScalableImage 类的源代码是:
package de.tu_freiberg.informatik.vonwenckstern.client;
// class is written by Michael von Wenckstern, and is also used in ist diploma Thesis
// (this is only for my super visor, that he does not think I copied it from stackoverflow
// without mention the source) - this class is free to use for every body
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Image;
public class ScalableImage extends Image {
private int width;
private int height;
private ImageResource res;
public ScalableImage(ImageResource res, int width, int height) {
this.setUrl(res.getSafeUri());
this.res = res;
this.width = width;
this.height = height;
}
@Override
public void onLoad() {
int widthOfBigImage = this.getOffsetWidth();
int heightOfBigImage = this.getOffsetHeight();
double scaleX = width / res.getWidth();
double scaleY = height / res.getHeight();
this.setResource(res);
DOM.setStyleAttribute(getElement(), "backgroundPosition", Integer.toString((int) (res.getLeft() * -1 * scaleX))+"px "+
Integer.toString((int) (res.getTop() * -1 * scaleY))+"px ");
DOM.setStyleAttribute(getElement(), "backgroundSize", Integer.toString((int) (widthOfBigImage * scaleX))+"px "+
Integer.toString((int) (heightOfBigImage * scaleY))+"px ");
this.setPixelSize((int) (res.getWidth()* scaleX), (int) (res.getHeight() * scaleY));
}
}
您可以按如下方式使用此类:
rootPanel.add(new ScalableImage(Images.Util.getImages().img0(), 60, 60));
如果将此类与 PushButton 一起使用,则必须将 PushButton 添加到 RootPanel,否则不会调用 onLoad() 函数。示例源代码如下所示:
for(ImageResource imRes: latexIconsClientBundle) {
ScalableImage im = new ScalableImage(imRes, 60, 60);
RootPanel.get().add(im); // PushButton class does not fire onAttach event, so we need to attach the image to the RootPanel
PushButton btn = new PushButton(im);
btn.setPixelSize(60, 60);
if(++col > 9) {
row++;
col = 0;
}
this.setWidget(row, col, btn);
}