Redeem Now
Read More
Read now

Split A Single Image into parts (just like sprite for HTML)

Save

In this blog, we will learn to split a single image into parts(just like sprite for HTML) in your android application.

If you don’t know what exactly sprite image is here is what “w3schools” definition :

An image sprite is a collection of images put into a single image.

A web page with many images can take a long time to load and generates multiple server requests.

Using image sprites will reduce the number of server requests and save bandwidth.

-https://www.w3schools.com

For more details on Sprite, you can read their whole article from here.

After getting a general idea of what a sprite image is, now we will look into how we can simply implement similar functionality in android.

APPROACH :

  1. We will use an image library for faster implementation to get an image from a URL (I have used glide, you can use any library or your own code to get the image from URL).
  2. Firstly we will extract the image as a bitmap from the Url. ( Let’s call this base_bitmap).
  3. Now, we will break this bitmap( base_bitmap ) into a list of bitmaps depending how much part do we need in our single image view.
  4. After this, we will simply iterate this list and add each bitmap into image view inside a Grid layout.

CODE :

Here I am having a sprite image with 15 images, with 5 rows and 3 columns.

and I have made Grid layout with 3 columns and 5 rows

activity_main.xml

For Handling Image and processing it further, I have made a separate class ImageHelper.java

And in our MainActivity.java file, I just called the ImageHelper function like this :

And it is done.

Just for your reference what we achieved through this code block :

Original Sprite Image :

 

Image in our app :

 

See it’s easy and  simple.

Thanks for reading this article.

Keep Coding and Keep sharing 🙂

. . .

Comments (2)

Add Your Comment

  • Daniele
    Hi, My name is Daniele and I am trying to run your program, but I am a beginner and it took forever to adapt it to GLIDE4. Can you please help me call the ImageHelper function? mGridLayout, mImageUrl why? Thank you very much
    • anchit
      Hello,

      Please share your code with me or provide a snippet or share the stacktrace of your exact issue.

  • css.php
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just recieved your project brief and our expert will contact you shortly.
    Send Again
    Close