【问题标题】:How to reverse image of a rectangle in javafx如何在javafx中反转矩形的图像
【发布时间】:2021-08-27 06:02:38
【问题描述】:

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

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

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

另外,我已将我的矩形放在锚窗格中,如果知道这很重要的话。

【问题讨论】:

  • “反向”是什么意思?
  • 我将编辑我的问题,使其变得清晰。
  • 啊——我明白了:你想应用某种变换吗?
  • 不一定要转换。欢迎任何可行的解决方案。

标签: java javafx


【解决方案1】:

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

  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);
  }
}

您可以使用的另一种变换是旋转,但上面的更简单。

【讨论】:

  • 如果要镜像也可以设置比例为-1.0
  • 有趣。我不会想到的。我会更新我的答案,因为这要简单得多。
猜你喜欢
  • 2014-05-15
  • 2021-11-19
  • 2014-05-09
  • 2021-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-02
相关资源
最近更新 更多