Create your account

Already have an account? Login here

Create account

Creating Screenshots with the Ionic Cordova Screenshot Plugin

By Gary simon - Jul 28, 2017

I just finished building an app that needed the ability to create screenshots of the app user interface. Fortunately, there's an Ionic Cordova screenshot plugin ready to go!

Based on the documentation, usage looks straight forward, however, it does leave out some key information that might stump some users.

Therefore, in this screenshot tutorial, I'm going to cover every step and just about every scenario, step by step. Let's get started!

If you prefer watching video..

Be sure to Subscribe to the Official Coursetro Youtube Channel for more awesome videos!

Starting the Project

Whether it's Angular, Vue, Ionic, etc.. I'm always a big fan of starting projects with a CLI if one exists. So, be sure that your Ionic CLI is up to date before we begin:

$ npm install -g ionic@latest

At the time of recording this, my CLI version happens to be: 3.6.0

Once installed, let's use it to start the project:

$ ionic start screenshots blank
$ cd screenshots

Once the start command finishes, cd into screenshots to jump into the folder.

Installing the Screenshot Plugin

Once inside the screenshots folder, we need to install the Cordova and Ionic native screenshot plugin:

$ ionic cordova plugin add com.darktalker.cordova.screenshot
$ npm install --save @ionic-native/screenshot

Upon running the first command, you might be prompted with a question about whether or not you want to install the cli-plugin-cordova, at which point you hit "y".

Then, run the npm install command.

Next, we have to import the screenshot plugin to our app.module file.

Open /src/app/app.module.ts and add the following import:

import { Screenshot } from '@ionic-native/screenshot';

// Add Screenshot as a Provider in the Provider array:

@NgModule({

  // Other arrays removed for brevity

  providers: [
    StatusBar,
    SplashScreen,
    Screenshot,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})

Great! Now we're ready to rock and roll.

Taking Screenshots with Ionic

The Ionic Native Screenshot plugin allows you to take screenshots through two different methods. 

  • save(format, quality, filename) - This saves the screenshot to the phone's storage. 
  • URI(quality) - This takes a screenshot and returns it as a base64 encoded string. You would use this method if there's no need to save the actual photo to the phone's storage.

Our demo app will have 2 buttons, and each will call upon a method that will use both save and URI. That way, you can have knowledge and experience with how to use both methods that are available.

Open /src/pages/home/home.ts and import the screenshot plugin at the top of the component file:

import { Screenshot } from '@ionic-native/screenshot';

To use it, as with all other Ionic Native plugins, we have to create an instance of it through dependency injection within the constructor:

export class HomePage {

  constructor(public navCtrl: NavController, private screenshot: Screenshot) {

  }

}

Now, just above the constructor, let's add two properties. One will hold the image (either a file path or the base64 encoded string), and the other will be a boolean for helping to determine when a screenshot is being displayed:

export class HomePage {

  screen: any;
  state: boolean = false;

  constructor(public navCtrl: NavController, private screenshot: Screenshot) {

  }

}

Again, we'll have 2 methods. Our first method screenShot() will use the .save method for saving a screenshot to the phone's storage.

Add the following methods beneath the constructor:

  // Reset function we will use to hide the screenshot preview after 1 second
  reset() {
    var self = this;
    setTimeout(function(){ 
      self.state = false;
    }, 1000);
  }

  screenShot() {
    this.screenshot.save('jpg', 80, 'myscreenshot.jpg').then(res => {
      this.screen = res.filePath;
      this.state = true;
      this.reset();
    });
  }

I want the screenshot to disappear after 1 second in the app UI, so that you can try out the other method, which is why I created a reset() function.

Then, in the screenShot() method, on successful callback, we set this.screen to res.filePath

If you were to console.log(res), you would see it's an object, which contains the file path of the stored image. This is the value we will use for our img src.

Next, we set this.state to true, and then call our reset() method, which sets state to false after 1 second to hide the image.

Let's add the second method beneath the screenShot() method:

  screenShotURI() {
    this.screenshot.URI(80).then(res => {
      this.screen = res.URI;
      this.state = true;
      this.reset();
    });

As you can see, pretty much exactly the same with exception to 2 less parameters, and setting this.screen to res.URI, which contains the base64 encoded string. We can use this same exact value with the same img src.

Defining the Template

Head on over to /src/pages/home/home.html and paste the following:

<ion-content padding [class.newBG]="state">
  <button ion-button outline (click)="screenShot()">Screenshot (PIC)</button>
  <button ion-button outline (click)="screenShotURI()">Screenshot (URI)</button>

  <img src="{{ screen }}" *ngIf="state">
</ion-content>

Yep, 6 lines will define our app UI. 

First, we're using class binding to attach a .newBG CSS class if state is true. The only reason I'm doing this is to change the app's background color. Otherwise, if it's left the same, it becomes hard to see the actual screenshot, since the screenshot is an exact image of the same UI.

Next, we're doing simple click events to call upon the appropriate methods.

And finally, we have an image that uses interpolation to call upon the screen property, and an *ngIf conditional that shows the image only if state is true.

Let's give this some CSS. Visit the /src/pages/home/home.css file and paste the following css rulesets:

ion-content {
    background:#233B3B !important;
    text-align:center;
}
.newBG {
    background:#4C6E6E !important;
}
button {
    color:#1FB5B5 !important;
    border: 1px solid #1FB5B5 !important;
}

img {
    border: 5px solid #365454;
    width:70%;
    margin-top: 3em
}

Just some really basic stuff here, so there's not much to explain! Now we're ready to give it a go.

Testing it out

Unfortunately, because we're using an Ionic Native plugin, we can't use ng serve to test out the screenshot plugin. 

You could use the Ionic view app, but I'm going to run a couple commands and connect my phone to test it out.

First, we need to add a build platform. I'm using Android, so I'm going to run:

$ ionic cordova platform add android

This takes awhile, but after installing, I can now connect my phone (make sure your phone is in developer mode with USB debugging enabled), and run the following command to launch app on my connected phone:

$ ionic cordova run android

After a minute or so, assuming you have java and all of that good stuff already installed, the app should launch on your phone and you can click on the 2 buttons and watch the same exact screenshot being toggled on and off. 

This is to illustrate that both methods do the same thing, except one of them (URI) doesn't save the result to the phone.

Hopefully this was a help to you!

 


Share this post

Chat with us




Say something about this awesome post!