将GWTCanvas与ImageResource一起使用

时间:2011-02-26 07:39:19

标签: gwt

我想使用GWT的clientBundle功能,只使用GWTCanvas加载1个由多个精灵组成的图像。我最初的想法是将ImageResource转换为ImageElement,但显然这似乎不起作用:

public interface Bundle implements ClientBundle{
   public static Bundle INSTANCE = GWT.create(Bundle .class);
   @Source("/img/tile1.png")
   public ImageResource tile1()
}

final GWTCanvas canvas = new GWTCanvas(400,400);
canvas.drawImage(ImageElement.as(new Image(Bundle.INSTANCE.tile1()).getElement()), 0, 0);

我尝试首先将图像添加到RootPanel(强制加载),但这似乎也不起作用。也许时间不正确。有没有人知道如何使用GWTCanvas绘制imageResource?

6 个答案:

答案 0 :(得分:7)

这有效:(GWT 2.4)

    // load:
    SafeUri uri= imageResource.getSafeUri();        
    ImageElement imgElement= ImageElement.as((new Image(uri)).getElement());

    // render
    context.drawImage(imgElement, 0, 0);

答案 1 :(得分:3)

您可以使用数据URI从捆绑中获取图像,但您需要像处理远程图像一样管理异步。

final Image image = new Image(resources.imageResource().getURL());
RootPanel.get().add(image);
image.setVisible(false);
fetchedImage.addLoadHandler(new LoadHandler() {
  public void onLoad(LoadEvent event) {
    context.drawImage(ImageElement.as(image.getElement()), 0, 0);
  }
});

答案 2 :(得分:2)

以您想要的方式使用ClientBundled图像是不可能的。组合成一个大图像的图像显示为背景图像,其基于浏览器的特征以仅显示图像的一部分。 GWT称之为“剪辑”。模式。因此,当您尝试获取该图像的元素时,实际的src标记为空,因为图像是背景图像。如果要在“画布”上显示图像,则必须是图像的实际链接。

答案 3 :(得分:2)

您可以在创建图像时尝试使用ImageResource的getURL()方法:

canvas.drawImage(ImageElement.as(new Image(Bundle.INSTANCE.tile1().getUrl()).getElement(), 0, 0);

当使用带有GWT 2.2.0的Canvas类型的ClientBundle时,我遇到了同样的问题,这为我修复了它。

答案 4 :(得分:0)

他们是正确的,只需使用getSafeUri()代替getURL()

答案 5 :(得分:0)

Tom Fishman的解决方案对我不起作用,因为在我调用canvas.drawImage()时没有加载图像。此解决方案有效(也适用于大图像):

    // Create Image
    SafeUri uri = resource.getSafeUri();
    Utils.console("URI: "+ uri);
    final Image img = new Image(uri);

    // Add the image to the RootPanel to force the image to be loaded.
    RootPanel.get().add(img);

    // The image has to be added to the canvas after the image has been loaded.
    // Otherwise the bounding box of the image is 0,0,0,0 and nothing will be drawn.
    img.addLoadHandler(new LoadHandler() {
        @Override
        public void onLoad(LoadEvent event) {
            // Create the image element.
            ImageElement imgElement = ImageElement.as(img.getElement());

            // Render the image on the canvas.
            context2d.drawImage(imgElement, offsetX, offsetY);

            // Delete the image from the root panel.
            RootPanel.get().remove(img);
        }
    });
相关问题