Android支持三种bitmap文件格式:.png (推荐), .jpg (接受), .gif (不支持).
Bitmap文件
这个是我们经常使用的,就是直接将图片资源放在res/drawable目录下,然后在就可以直接通过资源id进行使用。
位置:
res/drawable/filename.png (.png, .jpg, or .gif),资源id就是它的文件名
使用方式:
在Java文件中:R.drawable.filename
例如:
Resources res = getResources();
Drawable drawable = res.getDrawable(R.drawable.myimage);
在XML文件中:@[package:]drawable/filename
例如:
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/myimage" />
XML Bitmap
这是xml形式的bitmap,同样是将xml文件放在res/drawable目录下,然后在就可以直接通过资源id进行使用。
事实上这个xml形式的图片资源最终被解析为一个BitmapDrawable类型的对象.
使用方式跟上面直接使用Bitmap文件是一样的,只是一个是图片资源,一个是xml资源,xml资源对应的本质上也是BitmapDrawable资源。
具体xml的语法如下:
<?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:mipMap=["true" | "false"]
android:tileMode=["disabled" | "clamp" | "repeat" | "mirror"] />
android:src 对应的是一个图片资源
android:antialias 是否抗锯齿
android:dither 是否图像抖动处理,当每个颜色值以低于8位表示时,对应图像做抖动处理可以实现在可显示颜色总数比较低(比如256色)时还保持较好的显示效果。
android:filter 当图片压缩或者拉伸是否平滑处理
android:gravity 设置图片的对齐方式
android:mipMap 是否开启mipmap暗示
android:tileMode
disabled:不做其他处理
clamp:如果着色器绘制其原有的边界外,复制边缘颜色
repeat:水平和垂直方向重复图片
mirror:水平和垂直方向重复图片,但是它会调整图片,保证图片的衔接
例如:
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/icon"
android:tileMode="repeat" />
前面说过XML Bitmap对应的其实就是BitmapDrawable,他会将xml资源解析为BitmapDrawable对象,下面我们来说说BitmapDrawable
在xml中我们是通过属性来进行设置的,其实我们也可以直接使用代码来进行处理。
例如:
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.beauty1);
BitmapDrawable bd = new BitmapDrawable(bitmap);
bd.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
bd.setDither(true);
view.setBackgroundDrawable(bd);
https://developer.android.com/guide/topics/resources/drawable-resource.html#Bitmap
https://developer.android.com/reference/android/graphics/drawable/BitmapDrawable.html