JAVAFX webview 图片化 截图

public void start(Stage primaryStage) throws Exception {

final WebView view = new WebView();

 

Scene scene = new Scene(view, 310, 310);

primaryStage.setScene(scene);

 

final WebEngine webEngine = view.getEngine();

webEngine.load(this.getClass().getResource("web/index.html")

.toExternalForm());

 

primaryStage.show();

 

// 方式1. 监听webEngine加载进度,可能页面加载不完整

webEngine.getLoadWorker().stateProperty()

.addListener(new ChangeListener<State>() {

@Override

public void changed(ObservableValue<? extends State> ov,

State oldState, State newState) {

if (newState == State.SUCCEEDED) {

snapshot(view);

}

}

});

 

// 方式2. 使用Transition设定延时

PauseTransition ptr = new PauseTransition(Duration.seconds(3));

ptr.setOnFinished(new EventHandler<ActionEvent>() {

 

@Override

public void handle(ActionEvent event) {

snapshot(view);

}

});

ptr.play();

 

//方式3. 使用Task设定延时

Task<String> task = new Task<String>() {

 

@Override

protected String call() throws Exception {

Thread.sleep(5000);

return null;

}

};

task.setOnSucceeded(new EventHandler<WorkerStateEvent>() {

 

@Override

public void handle(WorkerStateEvent event) {

snapshot(view);

}

});

new Thread(task).start();

 

// 方式4. 自己实现多线程调用,较麻烦

new Thread(){

public void run() {

try {

Thread.sleep(7000);//该命令不可直接在Fx用户线程执行,否则会导致前台的渲染线程暂停,页面不会被加载

Platform.runLater(new Runnable() {

 

@Override

public void run() {

snapshot(view);//在后台线程中不可以直接操作UI,需要借助runLater

}

});

} catch (InterruptedException e) {

e.printStackTrace();

}

};

}.start();

}

 

 

public void snapshot(Node view) {

Image image = view.snapshot(null, null);

try {

ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png",

new File("f:\\" + System.currentTimeMillis() + ".png"));

} catch (IOException e) {

e.printStackTrace();

}

}

你可能感兴趣的:(webView)