Android Drawable --Bitmap xml

XML Bitmap是定义在XML文件当中,指向一个位图文件的资源。这样就为原生的位图文件起了一个别名。在XML定义时可以为位图定制诸如图像抖动或是平铺等额外属性。

文件存放位置:
res/drawable/filename.xml

语法:

1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="utf-8"?>
<bitmap
xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@[package:]drawable/drawable_resource"
android:antialias=["true" | "false"]
android:dither=["true" | "false"]
android:filter=["true" | "false"]
android:gravity=["top" | "bottom" | "left" | "right" | "center_vertical" |
"fill_vertical" | "center_horizontal" | "fill_horizontal" |
"center" | "fill" | "clip_vertical" | "clip_horizontal"]
android:tileMode=["disabled" | "clamp" | "repeat" | "mirror"] />

android:antialias——开启或关闭抗锯齿

android:dither——开启或关闭图像抖动(如果位图与显示屏幕的像素配置不相同时会用到,比如一张ARGB 8888位图和一个RGB565的显示屏)

android:filter——开启或关闭滤镜。当收缩或是拉伸位图时使用这个来使位图看上去更平滑。

android:gravity——当位图大小比它所在的容器小的时候,使用这个属性来决定位图在容器中的位置。可取的值有:top、bottom、left、right、center_vertical、fill_vertical(纵向缩放位图使之与容器等高)、center_horizontal、fill_horizontal(横向缩放位图使之与容器等宽)、center、fill(纵向与橫向都缩放使之完全铺满容器,这也是默认值)、clip_vertical(呃。。。)、clip_horizontal(呃。。。)。

android:tileMode——定义平铺模式。如果定义了,那么位图将会重复,并且Gravity属性将失效。可取的值有disabled(默认值,不启用平铺)、clamp(复制位图边缘的颜色来填充容器剩下的空白部分)、repeat(复制整个位图来填充容器)、mirror(与repeat类似,但是是交替的镜像复制,即相邻的两张是镜像对称的)

例:tileMode(平铺)
它的效果类似于 让背景小图不是拉伸而是多个重复(类似于将一张小图设置电脑桌面时的效果)

1
2
3
4
5
6
7
8
9
<xml version="1.0" encoding="utf-8"?>  
<LinearLayout
android:id="@+id/MainLayout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="@drawable/backrepeat"
>

backrepeat.xml

1
2
3
4
5
<bitmap   
xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/repeatimg"
android:tileMode="repeat"
android:dither="true" />

代码方式:

1
2
3
4
5
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);  
BitmapDrawable bd = new BitmapDrawable(bitmap);
bd.setTileModeXY(TileMode.REPEAT , TileMode.REPEAT );
bd.setDither(true);
view.setBackgroundDrawable(bd);

参考:关于android布局的两个属性dither和tileMode
Android Drawable —Bitmap xml