Using assets

In this recipe, we will learn how we can load and use assets.

Getting ready

As an example for this recipe, we will load and display an asset image.

Place an image file inside the assets folder in your project directory and name it image.png.

Include the following files at the top of your source code:

#include "cinder/gl/Texture.h"
#include "cinder/ImageIO.h"

Also add the following useful using statements:

using namespace ci;
using namespace ci::app;
using namespace std;

How to do it…

As an example, we will learn how we can load and display an image asset. Perform the following steps to do so:

  1. Declare a ci::gl::Texture object:
    gl::Texture image;
  2. In the setup method let's load the image asset. We will use a try/catch block in if it is not possible to load the asset.
        try{
            image = loadImage( loadAsset( "image.png" ) );
        } catch( ... ){
            console() << "asset not found" << endl;
        }
  3. In the draw method we will draw the texture. We will use an if statement to check if the texture has been successfully initialized:
    if( image ){
      gl::draw( image, getWindowBounds() );
        }

How it works…

The first application uses an asset Cinder, which will try to find its default assets folder. It will begin by searching the executable or application bundle folder, depending on the platform, and continue searching its parent's folder up to five levels. This is done to accommodate for different project setups.

There's more…

You can add an additional assets folder using the addAssetDirectory method, which takes a ci::fs::path object as a parameter. Every time Cinder searches for an asset, it will first look in its default asset folder and then in every folder the user may have added.

You can also create subfolders inside the assets folder, for example, if our image was inside a subfolder named My Images, we would type in the following code snippet in the setup method:

try{
     image = loadImage( loadAsset( "My Images/image.png" ) );
}catch( ... ){
     console() << "asset not found" << endl;
 }

It is also possible to know the path where a specific folder lies. To do this, use the getAssetPath method, which takes a ci::fs::path object as a parameter with the name of the file.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.111.92