我正在使用JavaFX並希望使用固定像素大小的畫布,可以縮放以填充窗口,並在窗口大小調整時增大。Java FX縮放的畫布
我爲我的FXML使用了SceneBuilder。
更新2015年5月30日。我意識到我已經指出了這個問題不好。我所追求的是Canvas組件不被調整大小;即內部柵格維度保持不變,而是對其應用縮放和轉換,以便填充可用空間。
我的出發點是:
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 FX控制器:
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);
}
}
Java的主要應用:
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);
}
}
我明白爲什麼現有的代碼在窗口生長時不能縮放畫布,但爲了實現這個目的我需要添加什麼?
另外我還需要縮放的Canvas來保持其底層縱橫比(如其像素寬度和高度所指定的),並且在包圍節點的縱橫比與Canvas的縱橫比不相同的情況下也保持在封閉節點的中心位置。
感謝任何幫助。
Oracle的Ensemble 8示例應用程序包含[可調整大小的畫布示例](http:// hg。 openjdk.java.net/openjfx/8u40/rt/file/eb264cdc5828/apps/samples/Ensemble8/src/samples/java/ensemble/samples/graphics2d/canvas/SanFranciscoFireworks.java#l112)。 – jewelsea