Reputation: 547
Is there a way to cut a Polygon if a part of it is getting out of it's AnchorPane?
I could try subtracting the Polygon with a rectangular shape but I wonder if there is a simpler way.
The image shows an example of a polygon getting out of the AnchorPane.
Edit: I tried setting max width and height to the AnchorPane, but it's not working.
Upvotes: 0
Views: 162
Reputation: 924
You need to use clip.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class ClipApp extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
Polygon hexagon = new Polygon();
hexagon.getPoints().addAll(new Double[]{
50., 0.,
150.0, 0.,
200.0, 100.0,
150.0, 200.0,
50.0, 200.0,
0., 100.0,
});
hexagon.setFill(Color.YELLOW);
AnchorPane anchorPane = new AnchorPane(hexagon);
anchorPane.setStyle("-fx-background-color: purple");
anchorPane.setPrefSize(200, 200);
anchorPane.setMinSize(Region.USE_PREF_SIZE, Region.USE_PREF_SIZE);
anchorPane.setMaxSize(Region.USE_PREF_SIZE, Region.USE_PREF_SIZE);
Rectangle rectangle = new Rectangle();
rectangle.widthProperty().bind(anchorPane.widthProperty());
rectangle.heightProperty().bind(anchorPane.heightProperty());
AnchorPane.setLeftAnchor(hexagon, 50.);
AnchorPane.setTopAnchor(hexagon, 50.);
StackPane stackPane = new StackPane(anchorPane);
stackPane.setStyle("-fx-background-color: blue");
stackPane.setPrefSize(400, 400);
Button button = new Button("Clip");
VBox vBox = new VBox(stackPane, button);
Scene scene = new Scene(vBox);
stage.setScene(scene);
stage.show();
button.setOnAction(event -> {
if (anchorPane.getClip() == null) {
button.setText("Unclip");
anchorPane.setClip(rectangle);
} else {
button.setText("Clip");
anchorPane.setClip(null);
}
});
}
}
Upvotes: 1