Sunday, June 15, 2014

How to make a screenshot in the games with Starling Framework?



Yep. Making a screenshot in the mobile games is a piece of cake. In the mobile devices (either iOS or Android), you could press the home button and the lock button simultaneously to achieve it.

However, sometimes we may want to implement this screenshot function inside the games. Reason? To capture a specific region of the screen.

Here, i am talking about using the Starling version 1.4.1 (will update soon with the 1.5.1).

In fact, with some searches, you may come across some articles about making a screenshot easily. But the thing is, in my opinions, those aren't complete enough. Below shows the complete snippet of codes of doing it.


1. Generate a BitmapData with a single line of code

var screenBitmapData:BitmapData = Starling.current.stage.drawToBitmapData();

To our delight, the latest Starling Framework has performed all the dirty works for us, with the 'drawToBitmapData()' function.

2. Encode the BitmapData and store it inside the byte array

var arrbyte:ByteArray = new ByteArray();
screenBitmapData.encode(new Rectangle(0, screenBitmapData.height/2, screenBitmapData.width, screenBitmapData.height/2), new JPEGEncoderOptions(), arrbyte);

Here, what i am doing is that i store the bitmap data inside a byte array, with some parameters such as the dimensions and the type of compressions (jpeg).

3. Write the array bytes into the File System

var fileHandle:File = new File(File.documentsDirectory.url + "/Pictures/YourGame/" + "Filename.jpg");
var fileAccess:FileStream = new FileStream();
    fileAccess.open(fileHandle,FileMode.WRITE);
    fileAccess.writeBytes(ba,0,ba.length);
    fileAccess.close();

With the byte array, you can perform the last step - Saving inside the file system. Here, you may specify which directory and the file name as you wish.

Is that all? Something missing?
Yep. There is one more question: How to generate unique file names for unlimited screenshots?
It isn't complicated after all. Just a reminder, you may use the "Current time" for the file naming purposes. For example:

var currentDateTime:Date = new Date();
var strRandomFileName:String = currentDateTime.toUTCString();

With this, the task of making screenshots is thoroughly complete. Hope this helps :)

No comments:

Post a Comment