我有以下问题:我正在编写一个像空白纸一样的程序,您可以在其中写(免费手写),插入文本,添加图像,添加PDF等...对于一个特定功能,我需要将用户添加到窗格的节点转换为图像。值得庆幸的是,Javafx节点提供了一个不错的方法:
public void snapshot(...)
但是有一个问题:当我试图制作文本对象的快照时,它们会失败。我可以拍摄快照的唯一节点是javafx.scene.text.text。以下课程失败:
javafx.scene.control.TextArea
javafx.scene.web.WebView
这是一个说明我的问题的示例:
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.control.TextArea;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
TextArea textArea = new TextArea("Lorem Ipsum is simply dummy text"
+ " of the printing and typesetting industry. Lorem Ipsum has been n"
+ "the industry's standard dummy text ever since the 1500s, when an n"
+ "unknown printer took a galley of type and scrambled it to make a typen"
+ " specimen book. It has survived not only five centuries, but also then"
+ " leap into electronic typesetting, remaining essentially unchanged. Itn"
+ " was popularised in the 1960s with the release of Letraset sheets containingn"
+ " Lorem Ipsum passages, and more recently with desktop publishing software n"
+ "like Aldus PageMaker including versions of Lorem Ipsum");
SnapshotParameters snapshotParameters = new SnapshotParameters();
snapshotParameters.setFill(Color.TRANSPARENT);
Image img = textArea.snapshot(snapshotParameters, null);
ImageView imgVw = new ImageView( img );
System.out.printf("img.width: %s height: %s%n", img.getWidth(), img.getHeight()); // <= width and height of the image img is 1:1! WHY?
Pane pane = new Pane();
pane.getChildren().addAll(imgVw);
Scene scene = new Scene(pane, 800,800);
pane.setMinWidth(800);
pane.setMinHeight(800);
pane.setMaxWidth(800);
pane.setMaxHeight(800);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
我可以通过创建一个Javafx.scene.text.text-object来想到一个工作,然后对此进行快照。但这将失败。
预先感谢您的帮助!
textarea需要在拍摄之前是一个场景。在快照调用之前,将以下行添加到您的代码中,并且代码将按照您的期望工作:
Scene snapshotScene = new Scene(textArea);
快照Javadoc中提到了此要求:
注意:为了正确运行CSS和布局,节点必须 成为场景的一部分(场景可能附加到舞台上,但不需要 是)。