Using image sprites on android

mattyp picture mattyp · Apr 20, 2011 · Viewed 19.6k times · Source

I have an image (588x449) sprite with a collection of different team logos. In Android I have the corresponding ImageView displaying this:

        <ImageView android:id="@+id/image_team_logo" 
            android:src="@drawable/teamheaderssprite" 
            android:layout_height="25dp" 
            android:layout_marginLeft="5dp" 
            android:layout_marginTop="10dp" 
            android:layout_width="296dp" android:scaleType="matrix"/>   

The above will correctly display the piece of my image in the upper left hand corner. My issue is I want to be able to move the position in the image being displayed so I can jump to another area in the sprite. This is pretty common practice in html/css, I am just not seeing a 'position' type property in android xml.

Answer

Dan Lew picture Dan Lew · Apr 20, 2011

You can't use sprites in the same way on Android you can with HTML. There is one way I can think of to simulate sprites though: Lay the sprite out entirely horizontally (or vertically), then use a ClipDrawable to define each level as a new part of the sprite. Then define the level of each View as appropriate. (If the images in the sprite aren't all the same size, you may need to use InsetDrawable as well.)

However, I would seriously rethink using sprites in Android. There are reasons why web pages use sprites, and it's not because they're easier - it's because it speeds up webpages because you don't have to make multiple HTTP requests. Since the images will already be in your release APK, you don't gain anything by spriting them.

Not only that, but you're doing some harm by spriting on Android:

  1. Memory constraints on some Android phones are much lower than you might expect. If the entirety of your graphics are in memory at any given time, that lowers the amount of memory you have for everything else.

  2. Sprites will be harder to handle once you start writing for different screen densities (ldpi, mdpi, hdpi).