Javafx 根据它的父控件缩放控件

Javafx scale a control according to it's parent

我正在用 Javafx 编写一个带有掩码的新 Imageview。 遮罩可以根据鼠标的方向显示。 使用时间线使其运行良好。但是当面具离开时,面具仍然可见。 我想隐藏图像之外的蒙版部分。我该如何缩放它?

鼠标进入时: 当鼠标离开时:

还有我的动画代码

private void leftOut() {
    KeyFrame k1 = new KeyFrame(Duration.ZERO, new KeyValue(mask.translateXProperty(), 0));
    KeyFrame k2 = new KeyFrame(time, new KeyValue(mask.translateXProperty(), control.getWidth()*-1.0));
    timeline = new Timeline();
    timeline.getKeyFrames().addAll(k1,k2);
    timeline.play();
}

其他方向同理

您根本不需要调整蒙版的大小。只需对其应用与图像大小相同的剪辑:

Image image = new Image("https://upload.wikimedia.org/wikipedia/commons/thumb/b/b1/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF.jpg/164px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF.jpg");
ImageView imageView = new ImageView(image);

// init mask
Label mask = new Label("SomeText");
mask.setMaxSize(Region.USE_PREF_SIZE, Region.USE_PREF_SIZE);
mask.setPrefSize(image.getWidth(), image.getHeight());
mask.setStyle("-fx-background-color: rgba(255, 255, 255, 0.6);");
mask.setAlignment(Pos.CENTER);

// create clip
Rectangle clip = new Rectangle(image.getWidth(), image.getHeight());
mask.setClip(clip);

// keep clip in position horizontally in root
clip.translateXProperty().bind(mask.translateXProperty().negate());

StackPane root = new StackPane(imageView, mask);
root.setPrefSize(500, 500);
root.setStyle("-fx-background-color: orange;");

// probably a bit simpler to use TranslateTransition instead of Timeline
TranslateTransition transition = new TranslateTransition(Duration.seconds(5), mask);
transition.setByX(image.getWidth());
transition.play();