2017-02-15 179 views
2

我有以下问题: 我正在写一个程序,就像一张空白纸,您可以在其上书写(自由手写),插入文本,添加图像,添加pdf等... 对于我需要将由用户添加到窗格的节点转换为图像的一个特定功能。值得庆幸的是,JavaFX的节点提供了一个很好的方法:拍摄JavaFX TextArea和WebView的快照

public void snapshot(...) 

但有一个问题:当我试图让他们失败文本的对象的快照。我可以拍摄快照的唯一节点是javafx.scene.text.Text。 以下类故障:

javafx.scene.control.TextArea 
javafx.scene.web.WebView 

下面是一个例子来说明我的问题:通过创建javafx.scene.text.Text-对象周围的工作

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 type\n" 
        + " specimen book. It has survived not only five centuries, but also the\n" 
        + " leap into electronic typesetting, remaining essentially unchanged. It\n" 
        + " was popularised in the 1960s with the release of Letraset sheets containing\n" 
        + " 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.web.WebView显示的格式化文本,这将失败。

在此先感谢您的帮助!

回答

1

在快照之前,TextArea需要为Scene。以下行添加到您的代码快照调用之前,代码将作为你希望:

Scene snapshotScene = new Scene(textArea); 

这要求在snapshot javadoc提到:

注意:为了让CSS和布局功能正常,节点必须是 是场景的一部分(场景可能附加到舞台,但不需要 )。

+0

非常感谢!完美的答案! – Soir