最简单的选择可能是转换节点,而不是尝试翻转图像本身。这样做的两个好处是:
- JavaFX 提供了简单的方法来转换(平移、旋转、缩放等)节点,并且
- 您可以为所有节点使用一个
Image。
@mipa 指出,在这种情况下使用的最简单的变换是缩放。要水平翻转节点,请使用node.setScaleX(-1)。要垂直翻转节点,请使用node.setScaleY(-1)。
这是一个显示所有四个所需方向的示例:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.ImagePattern;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
double width = 250;
double height = 250;
Image image = new Image(/* your image URL */, width, height, true, true);
ImagePattern fill = new ImagePattern(image);
Rectangle normal = new Rectangle(width, height, fill);
Rectangle horizontal = new Rectangle(width, height, fill);
Rectangle vertical = new Rectangle(width, height, fill);
Rectangle both = new Rectangle(width, height, fill);
flipNode(horizontal, true, false);
flipNode(vertical, false, true);
flipNode(both, true, true);
GridPane grid = new GridPane();
grid.setVgap(10);
grid.setHgap(10);
grid.setPadding(new Insets(10));
grid.setAlignment(Pos.CENTER);
grid.add(normal, 0, 0);
grid.add(horizontal, 1, 0);
grid.add(vertical, 0, 1);
grid.add(both, 1, 1);
primaryStage.setScene(new Scene(grid));
primaryStage.show();
}
private void flipNode(Node node, boolean horiztonally, boolean vertically) {
node.setScaleX(horiztonally ? -1 : 1);
node.setScaleY(vertically ? -1 : 1);
}
}
您可以使用的另一种变换是旋转,但上面的更简单。