Using image sprites on android

2019-02-12 10:34发布

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.

1条回答
欢心
2楼-- · 2019-02-12 11:17

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).

查看更多
登录 后发表回答