在javafx中更新/编辑图像的有效方法

时间:2018-06-07 14:50:47

标签: java image javafx

我有一个简单的平铺2D游戏(战列舰)我默认使用一个图像作为游戏区域(10x10)的图块,如果玩家放置船只或攻击等我需要更新它。我使用的方式是我将FX图像转换为awt图像,绘制了一些东西并转换回FX图像,因为我没有找到任何方法来绘制fx图像。我不能使用canvas,因为我需要ImageView的功能,它不支持画布并将图像转换为画布并返回图像可能与我当前的解决方案一样慢。 (通过"慢"我的意思是当我画一些东西时应用程序滞后几秒钟。)

我目前的代码:

static Image updateBackground(Game game, ImageView image, TileEntry... entries) {
    BufferedImage img = SwingFXUtils.fromFXImage(image.getImage(), null);
    Graphics2D g = img.createGraphics();

    int imgWidth = (int) (image.getImage().getWidth() / game.getOptions().getLengthX());
    int imgHeight = (int) (image.getImage().getHeight() / game.getOptions().getLengthY());

    for(TileEntry entry : entries) {
        Vector2i pos = entry.getPos();
        Tile tile = entry.getTile();
        Bounds tileBounds = game.getController().getTileBounds(pos);

        Image source = null;

        switch (tile) {
            case SHIP:
                source = images.get(ResourceType.SHIP);
                break;
        }

        if (source != null) {

            int posX = (pos.getX() * imgWidth) - 10;
            int posY = pos.getY() * imgHeight;

            BufferedImage swingImage = SwingFXUtils.fromFXImage(source, null);
            swingImage.getScaledInstance(imgWidth, imgHeight, java.awt.Image.SCALE_DEFAULT);

            g.drawImage(swingImage, posX, posY, null);
        }
    }

    return SwingFXUtils.toFXImage(img, null);
}

修改

我的代码使用canvas GraphicsContext

static Image updateBackground(Game game, ResizableCanvas canvas, TileEntry... entries) {
    GraphicsContext gc = canvas.getGraphicsContext2D();

    for(TileEntry entry : entries) {
        Vector2i pos = entry.getPos();
        Tile tile = entry.getTile();
        Bounds tileBounds = game.getController().getTileBounds(pos);

        switch (tile) {
            case SHIP:
                Image source = images.get(ResourceType.SHIP);
                gc.drawImage(source, tileBounds.getMinX(), tileBounds.getMinY());
                break;
            case HIT:
                gc.setStroke(javafx.scene.paint.Color.RED);
                gc.setLineWidth(10);
                gc.strokeLine(tileBounds.getMinX(), tileBounds.getMinY(), tileBounds.getMaxX(), tileBounds.getMaxY());
                gc.strokeLine(tileBounds.getMinX(), tileBounds.getMaxY(), tileBounds.getMaxX(), tileBounds.getMinY());
                break;
            case MARKED:
                gc.setStroke(javafx.scene.paint.Color.RED);
                gc.setLineWidth(10);
                gc.strokeLine(tileBounds.getMinX(), tileBounds.getMinY(), tileBounds.getMaxX(), tileBounds.getMaxY());
                gc.strokeLine(tileBounds.getMinX(), tileBounds.getMaxY(), tileBounds.getMaxX(), tileBounds.getMinY());
                break;
        }
    }

    return canvas.toImage();
}

0 个答案:

没有答案