1.Integer数组在程序中的使用,
<!-- 每一张小图片的信息数组依次为:x,y,w,h --> <integer-array name="box"> <item>250</item> <item>2</item> <item>65</item> <item>47</item> </integer-array>
使用数组资源的背景:
最近在做一款游戏,游戏的许多小图片都在一张大图上,要使用它们需要知道每张小图在大图上的:x,y,w,h
于是我就纠结了:要是一张一张的图片我可以使用 R.drawable.图片ID ,这回是好多图片在一个大图上,我该怎么使用呢?想了三种方案
1.在程序每个地方都采用Bitmap.createBitmap(bmp, ox, oy, mw, mh); 即写死小图位置大小(显然不可取)
2.定义一个enum为每张小图定义一个name,然后附加x,y,w,h信息(美工改图麻烦)
3.采用xml记录这张大图上的所有小图包括名称、x,y,w,h,然后有序初始化的时候解析xml保存所有小图x,y,w,h(算是还可以)
我采取了第三套方案,也成功的实现了,但是总感觉变捏,因为我的所有图片都是生成bitmap统一管理的,
/** * 每一个已初始化的位图的ID都是唯一的,包括大图上的小图 * 比如 Bodies1 定义了bodies1.png 上所有的小图的ID, * 必须保证所有的ID不会重合 */ private static List<Integer> resIds; //记录所有资源ID /** * 记录所有已初始化的位图的集合. * 包括 大图上的小图 */ private static HashMap<Integer, Bitmap> bmpsMap; //
后来我使用了枚举enum手动设定ID
/** * Bodies1 上图片ID对应枚举 * @author JianbinZhu * */ public static enum Bodies1{ /** * 投郑物系列 */ //木箱 box("box", 0xf0000001), box_small("box_small", 0xf0000002), //木桶 wood("wood", 0xf0000003), wood_small("wood_small", 0xf0000004), //木三角 triangle("triangle", 0xf0000005), triangle_small("triangle_small", 0xf0000006), //铁桶 metal("metal", 0xf0000007), metal_small("metal_small", 0xf0000008), //轮子 wheel("wheel", 0xf0000009), wheel_small("wheel_small", 0xf000000a), private final String name; //图片名 private final int id; //给的ID private Bodies1(String name, int id) { this.name = name; this.id = id; } public int getId() { return id; } public String getName() { return name; } }使用的时候传Bodies1参数,
几天突然想到Android xml 可以定义数组资源,
于是我就这样做
<!-- 每一张小图片的信息数组依次为:x,y,w,h --> <integer-array name="box"> <item>250</item> <item>2</item> <item>65</item> <item>47</item> </integer-array> <integer-array name="box_small"> <item>250</item> <item>160</item> <item>29</item> <item>21</item> </integer-array>然后这样读取,非常完美解决了我的问题
/** * 获取 img_bodies1.png 上的小图 * @param id 小图信息数组ID:x,y,w,h * @return */ public static Bitmap getBodies1Bitmap(int id) { Bitmap bmp = getBitmap(id); if(bmp == null){ int[] a = res.getIntArray(id); bmp = Bitmap.createBitmap(getBitmap(R.drawable.img_bodies1), a[0], a[1], a[2], a[3]); put(id, bmp); } return bmp; }