I would like to have use a Canvas of fixed pixel size, which can be scaled to fill a window and will grow when the window is resized.
I'm using SceneBuilder for my FXML.
My starting point is the following:
FXML:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.canvas.*?>
<?import javafx.scene.shape.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="scalingcanvas.FXMLDocumentController">
<center>
<AnchorPane BorderPane.alignment="CENTER">
<children>
<Canvas fx:id="canvas" height="200.0" width="200.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
</children>
</AnchorPane>
</center>
<top>
<Label text="top" BorderPane.alignment="CENTER" />
</top>
<bottom>
<Label text="bottom" BorderPane.alignment="CENTER" />
</bottom>
<left>
<Label text="left" BorderPane.alignment="CENTER" />
</left>
<right>
<Label text="right" BorderPane.alignment="CENTER" />
</right>
</BorderPane>
Java controller:
package scalingcanvas;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
public class FXMLDocumentController implements Initializable {
@FXML
private Canvas canvas;
@Override
public void initialize(URL url, ResourceBundle rb) {
System.out.printf("hi\n");
GraphicsContext g2d = canvas.getGraphicsContext2D();
double w = canvas.getWidth();
double h = canvas.getHeight();
g2d.setFill(Color.ALICEBLUE);
g2d.fillRect(0, 0, w, h);
g2d.setStroke(Color.BLUE);
g2d.strokeOval(0, 0, w, h);
g2d.strokeLine(0, 0, w, h);
g2d.strokeLine(0, h, w, 0);
}
}
Main app:
package scalingcanvas;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class ScalePanel extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
I understand why the existing code does not scale the Canvas when the window is grown, but what do I need to add to achieve this?
Also I need the scaled Canvas to maintain its underlying aspect ratio (as specified by its pixel width and height) and also remain centred in the enclosing node whet the enclosing node's aspect ratio is not the same as that of the Canvas.
Any help gratefully appreciated.