首页 > 解决方案 > 构图:如何使形状的尺寸适合图像?

问题描述

我正在制作一个基于 JavaFX 的游戏,该游戏使用宇宙飞船射击无人机来保卫你的基地。我想在图像周围包裹一个形状来为它创建一个碰撞箱。

这将允许激光在接触碰撞箱时对无人机造成损坏。它将使游戏看起来比激光击中隐形墙(形状的尺寸)更好,而不是实际图像。

我的问题是,有没有 JavaFX 提供的内置库来解决这个问题,或者你必须使用微积分公式来解决这个问题?

我试图查看 JavaFX 的 API,但似乎找不到任何有用的东西。

// Getting the images for the shapes
Image spaceCity = new Image("com/images/spaceCity.jpg");
Image spaceShip = new Image("com/images/spaceShip.png");

// Making the graphics
Rectangle space_Ship = new Rectangle(0, positionOfShipY, 191, 300);
Rectangle background = new Rectangle(0, 0, STAGE_WIDTH, STAGE_HEIGHT);

我在这里有我的例子(我不知道为什么堆栈溢出不允许我上传图片):

https://docs.google.com/document/d/1A8HJ61jhthBhd7wr6xrZNLlsTcQJNLUhTzrucvNY3BY/view?usp=sharing

标签: javaimagejavafxshapesgame-development

解决方案


根据图像设置形状的尺寸,并将两者放在StackPane

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class FxTest extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{

        String imagePath = "https://png.pngtree.com/png-clipart/20190118/ourmid/"
                          + "pngtree-hand-drawn-spaceship-grey-spaceship-alien-spaceship-blue"
                          + "-spaceship-border-png-image_450067.jpg";
        Image image =  new Image(imagePath);
        Rectangle rec = new Rectangle(0, 0, 50+image.getWidth(), 50+image.getHeight());
        rec.setFill(Color.AQUA);

        StackPane root = new StackPane();
        root.getChildren().add(rec);
        root.getChildren().add(new ImageView(image));
        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(null);
    }
} 

在此处输入图像描述


推荐阅读