ImageView中XML属性src和background的区别:html
background会根据ImageView组件给定的长宽进行拉伸,而src就存放的是原图的大小,不会进行拉伸。src是图片内容(前景),bg是背景,能够同时使用。java
此外:scaleType只对src起做用;bg可设置透明度,好比在ImageButton中就能够用android:scaleType控制图片的缩放方式android
如上所述,background设置的图片会跟View组件给定的长宽比例进行拉伸。举个例子, 36x36 px的图标放在 xhdpi 文件夹中,在854x480(FWVGA,对应hdpi)环境下,按照布局
xhdpi : hdpi : mdpi: ldip = 2 : 1.5 : 1 : 0.75编码
的比例计算,在FWVGA下,图标的实际大小应该是 27x27。spa
可是当我把它放到一个 layout_width = 96px, layout_height = 75px 的 LinearLayout,布局代码以下:.net
[html] view plaincopycode
<LinearLayout android:gravity="center" android:layout_width="96px" android:layout_height="75px" > orm
<ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/toolbar_bg"/> xml
</LinearLayout>
实际状况是,咱们获得的ImageButton的大小是 33x27,很明显width被拉伸了,这是咱们不想看到的状况。
解决方案一:
代码中动态显式设置ImageButton的layout_width和layout_width,以下
[java] view plaincopy
LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(27, 27);
layout.addView(imageButton, layoutParam);
不过,事实上咱们并不但愿在代码存在“硬编码”的状况。
解决方案二:
在你经过setBackgroundResource()或者在xml设置android:background属性时,将你的background以XML Bitmap的形式定义,以下:
[html] view plaincopy
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@id/toolbar_bg_bmp"
android:src="@drawable/toolbar_bg"
android:tileMode="disabled" android:gravity="top" >
</bitmap>
调用以下:
imageButton.setBackgroundResource(R.drawable.toolbar_bg_bmp)
或者
<ImageButton ... android:background="@drawable/toolbar_bg_bmp" ... />
若背景图片有多种状态,还可参照toolbar_bg_selector.xml:
[html] view plaincopy
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" >
<bitmap android:src="@drawable/toolbar_bg_sel" android:tileMode="disabled" android:gravity="top" />
</item>
<item >
<bitmap android:src="@drawable/toolbar_bg" android:tileMode="disabled" android:gravity="top" />
</item>
</selector>
如此,无论是经过代码方式setBackgroundResource()或XML android:background方式设置背景,均不会产生被拉伸的状况。