使用图片单元优化重复图片背景

来源:互联网 发布:python经典书籍推荐 编辑:程序博客网 时间:2024/05/17 22:25

在优化项目的过程,我发现有一些用作背景的图片,里面的内容是重复的,但因为屏幕的不同,为了适配很多屏幕,美工干脆切一个大图来,这样就带来了性能上的问题,我使用的是bitmap的方式解决的。

   有的兄弟就会问,图片太大,用九妹ninepatch搞定,我也想过这样做,但后来发现这个九妹是用来拉伸图片里面的一块指定固定位置来充满所要的背景,最常用的地方就是聊天对话文字表情项的显示,我现在使用到的bitmap xml是把一个小单元图不断的复制来填满所要的背景。

   讲完区别后,就上代码上图吧!

   之前使用到的代码如:

   <ImageView    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:background="@drawable/all_long_bg"/>

图片all_long_bg.png


效果如下图:


打出来的日志:

12-09 06:11:59.23511883-11883/com.research.tom.testtemo E/TestRepeatBgActivity: onCreate() start!!!!

12-09 06:11:59.25511883-11883/com.research.tom.testtemo D/dalvikvm: ---Heap option for 2268016

12-09 06:11:59.28011883-11883/com.research.tom.testtemo D/dalvikvm: GC_FOR_ALLOC freed 74K, 3%free 29930K/30656K, paused 13ms, total 13ms

12-09 06:11:59.28511883-11883/com.research.tom.testtemo E/TestRepeatBgActivity: onCreate() end!!!!

看到没有,这个Activity只加载这么一个图片,竟然被软件暂停了13ms(我的系统是4.4),从开始的235ms到结束的285ms,花了50ms,有点可怕,得优化。

我发现这个图片内容是重复的,所以把重复的内容切成一个小图片,如下图:

 

然后写了一个图片xml放于drawable文件夹中,unit_bmp_bg.xml

<?xml version="1.0" encoding="utf-8"?><bitmap xmlns:android="http://schemas.android.com/apk/res/android"    android:src="@drawable/small_unit_bg"    android:tileMode="repeat"    android:antialias="true"></bitmap>

把之前的代码修改下:

<ImageView    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:background="@drawable/unit_bmp_bg"/>

运行后如图所示:


打出的日志:

12-09 06:42:23.4574303-4303/com.research.tom.testtemo E/TestRepeatBgActivity: onCreate() start!!!!

12-09 06:42:23.4774303-4303/com.research.tom.testtemo E/TestRepeatBgActivity: onCreate() end !!!!

看到了吧,明显少了几行,也没有被暂停,从开始的457ms到结束477ms,只花了20ms,比之前减少了30ms

 

在做的过程中,我发现了另外一个问题,就是在某些固定高度时,有时会出一些问题,如下图

相应的代码:

<ImageView    android:layout_width="match_parent"    android:layout_height="15dp"    android:background="@drawable/unit_bmp_bg"/>

好难看呀,怎么办?

我们一想到的是在unit_bmp_bg.xml 文件中使用android:tileModeX="repeat"和android:tileModeY="clamp"来代替android:tileMode="repeat",想法非常好,干吧,运行一下,结果连重复铺开的效果没有,怎么回事?

Attribute titleModeX is only used in APIlevel 21 and highter(current min is 8)…

一看这个似乎明白了,android:tileModeX和android:tileModeY要使用到21以上,而我的4.4是16,所以被忽略了,官方给的建议就是建相应的layout-vNN,我感觉好麻烦呀,怎么办?用代码实现看行不行,于是一写,代码如下:

Bitmap bmp =BitmapFactory.decodeResource(getResources(),R.drawable.small_unit_bg);
BitmapDrawable bitmapDrawable = newBitmapDrawable(bmp);
bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT,Shader.TileMode.CLAMP);
ImageView testBgImgView=(ImageView)findViewById(R.id.testBgImgView);
testBgImgView.setBackgroundDrawable(bitmapDrawable);

我测试一下,有效果,就是说在低版本,android:tileModeX和android:tileModeY在xml里没效果,可以使用代码实现,但我仔细观察了一下,Shader.TileMode.CLAMP这个是他把底部的边缘颜色拉伸出来(英文: replicate the edge color if the shader draws outside of itsoriginal bounds),如果过高的话,也会不好看,所以高度最好还是wrap_content,好了,这些就是我几天的研究和实践,分享给大家,希望对大家有益!

                                                    

0 0
原创粉丝点击