问题演示
下面我们通过一个实例来演示一个我们在使用Drawable过程中经常会遇到的一个问题。
首先贴出UI布局文件,这里放了两个 ImageView
,它们的寬高不一样,而且对他们加以蓝色的背景。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:mz="http://schemas.android.com/apk/res-auto"
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="40dp"
android:orientation="vertical">
<ImageView
android:id="@+id/first"
android:layout_width="100dp"
android:layout_height="200dp"
android:scaleType="fitXY"
android:background="#1E90FF"/>
<ImageView
android:id="@+id/second"
android:layout_width="200dp"
android:layout_height="100dp"
android:layout_marginTop="50dp"
android:scaleType="fitXY"
android:background="#1E90FF"/>
</LinearLayout>
实例1
首先我们给第一个ImageView
设置一个显示图片。
final BitmapDrawable firstDrawable = (BitmapDrawable) getResources()
.getDrawable(R.drawable.test_mutate);
mFirstImage = (ImageView) findViewById(R.id.first);
mSecondImage = (ImageView) findViewById(R.id.second);
mFirstImage.setImageDrawable(firstDrawable);
看下面的效果,因为第二个我们没有设置前景图片,因此会现实背景图片。这个很正常,我们不会有什么疑问。
实例2
接下来我们在原来代码的基础上添加下面代码,为第二个ImageView
设置图片。
......
mSecondImage.setImageDrawable(firstDrawable);
看一下效果图,第一个图片的现实效果和实例1变的不一样了,你也许会感觉这个很正常,因为同一个Drawable
对象设置给两个大小不同的ImageView
,第二个尺寸改变以后第一个也跟着改变了。
实例3
那么我们再实例化一个Drawable
对象设置给第二个ImageView
。
final BitmapDrawable firstDrawable = (BitmapDrawable) getResources()
.getDrawable(R.drawable.test_mutate);
final BitmapDrawable secondDrawable = (BitmapDrawable) getResources()
.getDrawable(R.drawable.test_mutate);
mFirstImage = (ImageView) findViewById(R.id.first);
mSecondImage = (ImageView) findViewById(R.id.second);
mFirstImage.setImageDrawable(firstDrawable);
mSecondImage.setImageDrawable(secondDrawable);
看一下效果图,这下显示正常了,这个也可以理解,两个不同的Drawable
对象设置给不同的ImageView
,他们互不干涉。那么真的是这样的吗?再接着往下面看。
实例4
我们在上面的代码的基础上把第二个Drawable
的 alpha 设置为15 0 。
......
secondDrawable.setAlpha(150);
看下面效果图,奇怪的现象发生了,第一个图片也变成半透明的了,为什么呢?