How to make a sprite from URL in cocos2d-x

Hello friends. In this tutorial I am going to explain how you will be making a sprite from any URL on Internet
I am using two URLs
1. http://lptpl.info/9.png
2. https://dl.dropboxusercontent.com/u/37517735/icon_test.jpg

So these are the two images I will be using to create the sprite

Step 1:
Step 1 is as simple. Just create a new project in cocos2d-x

Step 2:
Now just remove the extra matter in your HelloWorldScene.h so that it looks like

Step 3:
Now in your HelloWorldScene.h, add the following headers and namespaces

HttpClient.h is used for the request and response of the URL

Step 4:
Now we add some labels and functions such that the class looks like

Step 5:
In your HelloWorldScene.cpp class add the following after the after the inclusion of HelloWorldScene.h class

These two URLs will be used for fetching the images

Step 6:
Now in your init function just add the label and a button. On button click I will be loading the URL and will be making it a sprite
So now your init function looks like

Step 7:
On button click the downLoadImage() function is called

The definition of downLoadImage() function is as follows

Here I have set the name as img.png. This means that the image downloaded will be saved as img.png in your simulators library folder. I will show you the path later on in the next steps. Then the responsecallback is set to call another function onImageDownLoaded()
The definition of onImageDownLoaded() is as follows

Your image will be stored in somewhat path like this
Path of Image

And now you are done. Now run the project
Output will be


Now change the URL and you can see other image


Hope it helped you and you liked it.

7,071 total views, 1 views today

Share this OnShare on FacebookTweet about this on TwitterShare on LinkedInShare on Google+

Leave a Reply