如果Android
UI开发,我们都知道,android默认的背景图属性中都是伸缩的,并未提及平铺背景图,但是在实际的开发过程中,你可能遇到过这样一个问题,那就是平铺背景图,如绘制虚线,绘制游戏背景等等。不久前项目开发过程中我也遇到了这样的要求,经过无穷的百度谷歌,总结了一下有三种常用的方式,下面,下面是描述和核心代码。
++ 最不常用的一种,看了就可以忘记了 ++++++++
第一种:自定义View绘制。即就是根据背景图以及背景图的大小,计算出所需要的行数和列数,然后利用View的onDraw()方法绘制即可。因为计算上和绘制是靠程序员控制的.
public static Bitmap createRepeater(int width, Bitmap
src){
int count = (width + src.getWidth() - 1) / src.getWidth();
Bitmap bitmap = Bitmap.createBitmap(width, src.getHeight(),
Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
for(int idx = 0; idx < count; ++ idx){
canvas.drawBitmap(src, idx * src.getWidth(), 0, null);
}
return bitmap;
}
++ 比较常用的一种 +++++++++++++++
第二种:利用android提供的另一种图片类型:bitmap类型的图片,格式如下:
encoding="utf-8"?>
android:src="@drawable/test"
android:tileMode="repeat"
>
属性说明
tileMode="repeat" : 表示背景图片重复
tileMode="disable": 表示背景图片不平铺,默认是拉伸
tileMode ="mirror" : 表示背景图片镜像显示
这种方法只能定义一种背景图,不能根据图片的背景绘制不同的平铺背景图。灵活性不高。
++ 常用 +++++++++++++++++++++++++++
第三种:利用背景图片的不同绘制不同的平铺背景,这个需要自定义View。在之地凝视的View的构造方法里初始化如下:
private void init() {
Drawable de =
this.getBackground();
BitmapDrawable bd = new
BitmapDrawable(drawableToBitmap(de));
bd.setTileModeXY(TileMode.REPEAT,
TileMode.REPEAT);
this.setBackgroundDrawable(bd);
}
//将图片的背景图转换为bitmap 类型
private Bitmap drawableToBitmap(Drawable d)
{
Bitmap bitmap =
Bitmap.createBitmap(d.getIntrinsicWidth(), d
.getIntrinsicHeight(),
d.getOpacity()
!= PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
:
Bitmap.Config.RGB_565);
Canvas canvas = new
Canvas(bitmap);
d.setBounds(0, 0,
d.getIntrinsicWidth(), d.getIntrinsicHeight());
d.draw(canvas);
return bitmap;
}