如何在javafx中反转矩形的图像

  • 本文关键字:图像 javafx java javafx
  • 更新时间 :
  • 英文 :


我有一个javafx应用程序,里面有一个矩形,我使用矩形.setFill((来用图像填充矩形。我想知道如何反转矩形的图像。(我想将其垂直和水平以及它们的组合反转。(

假设我放在矩形上的图像是蓝色的,右上角有一个红色的圆圈。我想要红色圆圈位于矩形的右下侧、左下侧和左上侧的图像。

我已经找到了一些Canvas和GraphicsContext的解决方案,但它们似乎不适用于Rectangle。有矩形的解决方案吗?

此外,如果重要的话,我已经把我的矩形放在了一个凤尾鱼中。

最简单的选择可能是变换节点,而不是尝试翻转图像本身。这有两个好处:

  1. JavaFX提供了转换(平移、旋转、缩放等(节点的简单方法,并且
  2. 可以对所有节点使用单个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);
}
}

您可以使用的另一种变换是旋转,但上述变换更容易。

最新更新