Sunday, January 18, 2015

Anansi: Screenshots


I'd like to get rid of the border around the screenshots of our game. Until now I did them with windows print screen key. JavaFX has a built-in snapshot command. So let's use that one.

Here's a small utility class that I created using a tutorial on the Oracle website.
package game.utils;

import java.io.File;
import java.io.IOException;

import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.WritableImage;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import javax.imageio.ImageIO;

public class Utils {

 /**
  * Take a screenshot of the scene in the given stage, open file save dialog and save it.
  * @param stage
  */
 public static void screenshot( Stage stage) {
  
  // take screenshot
     WritableImage image = stage.getScene().snapshot( null);

     // create file save dialog
     FileChooser fileChooser = new FileChooser();
     
     // title
        fileChooser.setTitle("Save Image");
        
        // initial directory
        fileChooser.setInitialDirectory(
                new File(System.getProperty("user.home"))
            );              
        
        // extension filter
        fileChooser.getExtensionFilters().addAll(
            // new FileChooser.ExtensionFilter("All Images", "*.*"),
            // new FileChooser.ExtensionFilter("JPG", "*.jpg"),
            new FileChooser.ExtensionFilter("PNG", "*.png")
        );
        
        // show dialog
        File file = fileChooser.showSaveDialog( stage);
        if (file != null) {
         
            try {
             
                // save file
                ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file);
                
            } catch (IOException ex) {
             
                System.err.println(ex.getMessage());
                
            }
        }
 }
 
}

We can use it by extending our KEY_RELEASED event handler. The utility method demands a stage as parameter, so we need to keep a reference of the primary stage in a global variable.
Stage primaryStage;
 
@Override
public void start(Stage primaryStage) {

    this.primaryStage = primaryStage;
    ...

}
         

The screenshot key will be F12.
...
 @Override
 public void handle(KeyEvent event) {
 
  // register key up
  keyboardBitSet.set(event.getCode().ordinal(), false);
 
  // take screenshot, open save dialog and save it
  if( event.getCode() == KeyCode.F12) {
   
   // pause game
   gameLoop.stop();
   
   // save screenshot
   Utils.screenshot( primaryStage);
  
   // resume game
   gameLoop.start();
  
  }
 
 }
...
And now we got nice PNG files without the windows border whenever we press the screenshot key:

No comments:

Post a Comment