当前位置: 移动技术网 > 移动技术>移动开发>Android > Android源码系列之深入理解ImageView的ScaleType属性

Android源码系列之深入理解ImageView的ScaleType属性

2019年07月24日  | 移动技术网移动技术  | 我要评论

做android开发的童靴们肯定对系统自带的控件使用的都非常熟悉,比如button、textview、imageview等。如果你问我具体使用,我会给说:拿imageview来说吧,首先创建一个新的项目,在项目布局文件中应用imageview控件,代码如下:

<?xml version="1.0" encoding="utf-8"?> 
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" 
 android:background="#bbaacc" > 
 
 <imageview 
 android:src="@drawable/ic_launcher" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
 android:background="#aabbcc" /> 
 
</linearlayout> 

        上边布局文件为了便于查看各种属性效果,故意加了两个背景颜色,这对我们今天的源码分析影响不大。接着运行一下代码,效果图如下:

        恩,不错,运行结果正如所愿,屏幕上显示的正是我们设置的图片,这时候心中不由欣喜imageview的使用就是这样简单,so easy嘛!呵呵,如果真是这么想那就大错特错了,上边的示例仅仅是在布局文件中使用了imageview的src,layout_width和layout_height这三个属性罢了,它其他的重要属性我们还没有用到,今天这篇文章就是主要结合源码讲解imageview的另一个重要的属性------scaletype,其他的一些属性等将来需要的话再做详细解说。好了,现在正式进入主题。
        scaletype属性主要是用来定义图片(bitmap)如何在imageview中展示的,姑且就认为是展示吧,系统给我们提供了8种可选属性:matrix、fitxy、fitstart、fitcenter、fitend、center、centercrop和centerinside。每一种属性对应的展示效果是不一样的,下面我们先来做一个实验来说明每一种属性的显示效果,我从之前的项目中挑选了两张图片,一张图片的实际尺寸是720*1152,另一张是我把第一张图翻转放缩得到的,它的实际尺寸是96*60,之所以采用两张图片是为了便于对比和观察结果,原图片如下:

        ok,测试图片准备好了,接下来我们在布局文件中分别使用scaletype的每一个属性值,我们开始写布局文件,内容如下:

<?xml version="1.0" encoding="utf-8"?> 
<scrollview xmlns:android="http://schemas.android.com/apk/res/android" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" 
 android:background="#bbccaa" > 
 
 <tablelayout 
 android:layout_width="match_parent" 
 android:layout_height="wrap_content" 
 android:padding="10dp" > 
 
 <textview 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
 android:layout_marginbottom="10dp" 
 android:text="图片尺寸的宽和高都远远大于imageview的尺寸" /> 
 
 <tablerow 
 android:layout_width="match_parent" 
 android:layout_height="wrap_content" > 
 
 <imageview 
 android:layout_width="300px" 
 android:layout_height="300px" 
 android:background="#aabbcc" 
 android:scaletype="matrix" 
 android:src="@drawable/test" /> 
 
 <imageview 
 android:layout_width="300px" 
 android:layout_height="300px" 
 android:layout_marginleft="10dp" 
 android:background="#aabbcc" 
 android:scaletype="fitxy" 
 android:src="@drawable/test" /> 
 
 <imageview 
 android:layout_width="300px" 
 android:layout_height="300px" 
 android:layout_marginleft="10dp" 
 android:background="#aabbcc" 
 android:scaletype="fitstart" 
 android:src="@drawable/test" /> 
 
 <imageview 
 android:layout_width="300px" 
 android:layout_height="300px" 
 android:layout_marginleft="10dp" 
 android:background="#aabbcc" 
 android:scaletype="fitcenter" 
 android:src="@drawable/test" /> 
 </tablerow> 
 
 <tablerow 
 android:layout_width="match_parent" 
 android:layout_height="wrap_content" 
 android:layout_margintop="5dp" > 
 
 <textview 
 android:layout_width="300px" 
 android:layout_height="wrap_content" 
 android:gravity="center" 
 android:text="matrix" /> 
 
 <textview 
 android:layout_width="300px" 
 android:layout_height="wrap_content" 
 android:gravity="center" 
 android:text="fitxy" /> 
 
 <textview 
 android:layout_width="300px" 
 android:layout_height="wrap_content" 
 android:gravity="center" 
 android:text="fitstart" /> 
 
 <textview 
 android:layout_width="300px" 
 android:layout_height="wrap_content" 
 android:gravity="center" 
 android:text="fitcenter" /> 
 </tablerow> 
 
 <tablerow 
 android:layout_width="match_parent" 
 android:layout_height="wrap_content" 
 android:layout_margintop="10dp" > 
 
 <imageview 
 android:layout_width="300px" 
 android:layout_height="300px" 
 android:background="#aabbcc" 
 android:scaletype="fitend" 
 android:src="@drawable/test" /> 
 
 <imageview 
 android:layout_width="300px" 
 android:layout_height="300px" 
 android:layout_marginleft="10dp" 
 android:background="#aabbcc" 
 android:scaletype="center" 
 android:src="@drawable/test" /> 
 
 <imageview 
 android:layout_width="300px" 
 android:layout_height="300px" 
 android:layout_marginleft="10dp" 
 android:background="#aabbcc" 
 android:scaletype="centercrop" 
 android:src="@drawable/test" /> 
 
 <imageview 
 android:layout_width="300px" 
 android:layout_height="300px" 
 android:layout_marginleft="10dp" 
 android:background="#aabbcc" 
 android:scaletype="centerinside" 
 android:src="@drawable/test" /> 
 </tablerow> 
 
 <tablerow 
 android:layout_width="match_parent" 
 android:layout_height="wrap_content" 
 android:layout_margintop="5dp" > 
 
 <textview 
 android:layout_width="300px" 
 android:layout_height="wrap_content" 
 android:gravity="center" 
 android:text="fitend" /> 
 
 <textview 
 android:layout_width="300px" 
 android:layout_height="wrap_content" 
 android:gravity="center" 
 android:text="center" /> 
 
 <textview 
 android:layout_width="300px" 
 android:layout_height="wrap_content" 
 android:gravity="center" 
 android:text="centercrop" /> 
 
 <textview 
 android:layout_width="300px" 
 android:layout_height="wrap_content" 
 android:gravity="center" 
 android:text="centerinside" /> 
 </tablerow> 
 </tablelayout> 
 
</scrollview> 

        为了快速进入今天文章主题,布局文件并没有按照平时开发中所遵循的android开发规范来写。布局中使用的是tablelayout标签嵌套tablerow的方式,分成两行,每一行是4列,恰好8种属性可以合理对比查看。当然了这里有更高效的写法来实现同样的效果,比如使用relativelayout布局等。
        在布局文件中我们定义了每个imageview的宽高都是固定的300像素,这个尺寸远小于或者是远大于测试的图片尺寸,另外为了便于观察效果我给每个imageview的背景都设置了颜色,接着运行大图和小图的测试结果,效果如下:

        通过上述实验结果对比,就可以得出部分属性的展示效果。比如fitxy属性,当imageview的属性设置成了fitxy时,图片的宽和高就会相应的拉伸或者是压缩来填充满整个imageview,注意这种拉放缩不成比例。当imageview的属性设置成了matrix时,如果图片宽高大于imageview的宽高时,图片的显示就是从imageview的左上角开始平铺,超出部分不再显示;如果图片宽高小于imageview的宽高时,图片的显示也是从imageview的左上角开始平铺,缺少部分空白显示出来或者是显示imageview的背景。以上仅仅是根据运行结果来得出的结果,权威结论还要通过查看源码来得出,本文分析的源码是android2.2版本。
        分析imageview的源码首先从它的构造方法开始,看一下构造方法里边都做了什么工作。构造方法如下:

public imageview(context context) { 
 super(context); 
 initimageview(); 
} 
 
public imageview(context context, attributeset attrs) { 
 this(context, attrs, 0); 
} 
 
public imageview(context context, attributeset attrs, int defstyle) { 
 super(context, attrs, defstyle); 
 initimageview(); 
 
 typedarray a = context.obtainstyledattributes(attrs, 
 com.android.internal.r.styleable.imageview, defstyle, 0); 
 
 drawable d = a.getdrawable(com.android.internal.r.styleable.imageview_src); 
 if (d != null) { 
 setimagedrawable(d); 
 } 
 
 ////////////////////////////////////////////////// 
 // 
 // 以下源码部分属性初始化不涉及主核心,不再贴出 
 // 
 ////////////////////////////////////////////////// 
 
 
 a.recycle(); 
 
 //need inflate syntax/reader for matrix 
} 

        通过查看构造方法发现,在三个构造方法中都调用了initimageview()这个方法,这个方法是干嘛使的,我们稍后在看。其次是根据在布局文件中定义的属性来初始化相关属性,在测试布局中我们仅仅是用了imageview的src,layout_width,layout_height和scaletype属性(background属性暂时忽略)。那也就是说在构造函数的初始化中就是对相关属性进行了赋值操作,通过解析src属性我们获取到了一个drawable的实例对象d,如果d是非空的话就把d作为参数又调用了setimagedrawable(d)函数,我们看看一下这个函数主要做了什么工作,源码如下:

/** 
 * sets a drawable as the content of this imageview. 
 * 
 * @param drawable the drawable to set 
 */ 
public void setimagedrawable(drawable drawable) { 
 if (mdrawable != drawable) { 
 mresource = 0; 
 muri = null; 
 
 int oldwidth = mdrawablewidth; 
 int oldheight = mdrawableheight; 
 
 updatedrawable(drawable); 
 
 if (oldwidth != mdrawablewidth || oldheight != mdrawableheight) { 
 requestlayout(); 
 } 
 invalidate(); 
 } 
} 

        此方法类型是public的,目的是干嘛使的不再解释了,注释上说的是把给定的drawable作为当前imageview的展示内容,接着是个条件判断,在刚刚完成初始化的时候mdrawable属性还没有被赋值此时为空,因此判断成立程序进入条件语句继续执行,在这里把属性mresource和muri归零操作并计入mdrawablewidth和mdrawableheight的初始值,紧接着把传递进来的drawable参数传递给了updatedrawable()方法,那我们继续跟进updatedrawable()看看这里边又做了什么操作,源码如下:

private void updatedrawable(drawable d) { 
 if (mdrawable != null) { 
 mdrawable.setcallback(null); 
 unscheduledrawable(mdrawable); 
 } 
 mdrawable = d; 
 if (d != null) { 
 d.setcallback(this); 
 if (d.isstateful()) { 
 d.setstate(getdrawablestate()); 
 } 
 d.setlevel(mlevel); 
 mdrawablewidth = d.getintrinsicwidth(); 
 mdrawableheight = d.getintrinsicheight(); 
 applycolormod(); 
 configurebounds(); 
 } else { 
 mdrawablewidth = mdrawableheight = -1; 
 } 
} 

        该方法首先进行了非空判断,此时mdrawable的值依然是空,所以条件判断不成立跳过此部分,紧接着把传递进来的非空参数d的字赋值给了属性mdrawable,到这里mdrawable才算是完成了赋值操作。然后又进行了条件判断,并设置d的callback为当前imageview(因为imageview的父类view实现了drawable的callback接口)接下来又把图片的宽和高分别赋值给了mdrawablewidth和mdrawableheight,紧接着又调用了applycolormod()方法,当我们没有给imageview设置透明度或者是颜色过滤器时该方法不会执行。然后调用configurebounds()方法,此方法是我们今天要讲的和scaletype属性息息相关的重点,不耽误时间了赶紧瞅一下源码吧,(*^__^*) 嘻嘻……

 private void configurebounds() { 
 if (mdrawable == null || !mhaveframe) { 
 return; 
 } 
 
 
 int dwidth = mdrawablewidth; 
 int dheight = mdrawableheight; 
 
 
 int vwidth = getwidth() - mpaddingleft - mpaddingright; 
 int vheight = getheight() - mpaddingtop - mpaddingbottom; 
 
 
 boolean fits = (dwidth < 0 || vwidth == dwidth) && 
 (dheight < 0 || vheight == dheight); 
 
 ////////////////////////////////////////代码块一//////////////////////////////////////// 
 
 if (dwidth <= 0 || dheight <= 0 || scaletype.fit_xy == mscaletype) { 
 /* if the drawable has no intrinsic size, or we're told to 
 scaletofit, then we just fill our entire view. 
 */ 
 mdrawable.setbounds(0, 0, vwidth, vheight); 
 mdrawmatrix = null; 
 
 ////////////////////////////////////////代码块二//////////////////////////////////////// 
 
 } else { 
 // we need to do the scaling ourself, so have the drawable 
 // use its native size. 
 mdrawable.setbounds(0, 0, dwidth, dheight); 
 
 
 if (scaletype.matrix == mscaletype) { 
 // use the specified matrix as-is. 
 if (mmatrix.isidentity()) { 
 mdrawmatrix = null; 
 } else { 
 mdrawmatrix = mmatrix; 
 } 
 
 ////////////////////////////////////////代码块三//////////////////////////////////////// 
 
 } else if (fits) { 
 // the bitmap fits exactly, no transform needed. 
 mdrawmatrix = null; 
 
 ////////////////////////////////////////代码块四//////////////////////////////////////// 
 
 } else if (scaletype.center == mscaletype) { 
 // center bitmap in view, no scaling. 
 mdrawmatrix = mmatrix; 
 mdrawmatrix.settranslate((int) ((vwidth - dwidth) * 0.5f + 0.5f), 
  (int) ((vheight - dheight) * 0.5f + 0.5f)); 
 
 ////////////////////////////////////////代码块五//////////////////////////////////////// 
 
 } else if (scaletype.center_crop == mscaletype) { 
 mdrawmatrix = mmatrix; 
 
 
 float scale; 
 float dx = 0, dy = 0; 
 
 
 if (dwidth * vheight > vwidth * dheight) { 
 scale = (float) vheight / (float) dheight; 
 dx = (vwidth - dwidth * scale) * 0.5f; 
 } else { 
 scale = (float) vwidth / (float) dwidth; 
 dy = (vheight - dheight * scale) * 0.5f; 
 } 
 
 
 mdrawmatrix.setscale(scale, scale); 
 mdrawmatrix.posttranslate((int) (dx + 0.5f), (int) (dy + 0.5f)); 
 
 ////////////////////////////////////////代码块六//////////////////////////////////////// 
 
 } else if (scaletype.center_inside == mscaletype) { 
 mdrawmatrix = mmatrix; 
 float scale; 
 float dx; 
 float dy; 
 
 if (dwidth <= vwidth && dheight <= vheight) { 
 scale = 1.0f; 
 } else { 
 scale = math.min((float) vwidth / (float) dwidth, 
 (float) vheight / (float) dheight); 
 } 
 
 dx = (int) ((vwidth - dwidth * scale) * 0.5f + 0.5f); 
 dy = (int) ((vheight - dheight * scale) * 0.5f + 0.5f); 
 
 
 mdrawmatrix.setscale(scale, scale); 
 mdrawmatrix.posttranslate(dx, dy); 
 
 ////////////////////////////////////////代码块七//////////////////////////////////////// 
 
 } else { 
 // generate the required transform. 
 mtempsrc.set(0, 0, dwidth, dheight); 
 mtempdst.set(0, 0, vwidth, vheight); 
 
 mdrawmatrix = mmatrix; 
 mdrawmatrix.setrecttorect(mtempsrc, mtempdst, scaletypetoscaletofit(mscaletype)); 
 
 ////////////////////////////////////////代码块八//////////////////////////////////////// 
 
 } 
 } 
 } 

        configureboundd()函数比较长,为了方便分析源码,我把该函数代码分成了8小块,每一个小块都是一个单独的逻辑。每一块的详解如下:
代码块一:
        该模块代码首先做了一个条件判断,如果当前mdrawable为空或者是mhaveframe为false则函数直接返回不再往下执行,由于后边的逻辑主要是根据scaletype属性的类型来判断图片的展示方式,所以再后来这个函数肯定是能往下走的通的,由于篇幅的原因不再深入讲解该函数的调用时机,我会在之后的文章中专门根据源码讲解一下android系统下view的绘制流程,在之后的绘制流程中会提到configurebounds()的调用时机。该代码块的逻辑是获取图片的宽高存储在dwidth,dheight中,然后又获取到了imageview的显示图片区域的宽高存放在vwidth和vheight中。然后定义了一个boolean类型的变量,该变量若为true就表示不需要对图片进行放缩处理。
代码块二:
        该代码块的逻辑是当获取到的图片尺寸的宽高未知或者是imageview的scaletype属性为fit_xy时,将mdrawable的显示边界设置成控件imageview的显示区域大小,并且把mdrawmatrix对象设置成null。需要说明的是setbounds方法用来设置drawable的绘制区域的,最终在imageview的ondraw方法中把mdrawable表示的图片绘制到imageview上。
代码块三:
        如果图片宽高不为0并且imageview的scaletype属性不是fit_xy时,就会把mdrawable的绘制区域设置成图片的原始大小。接着进行判断imageview的scaletype属性值是否是matrix,如果是matrix类型,就会把当前mmatrix赋值给mdrawmatrix。
代码块四:
        代码块四是一个if(fits)的判断,如果fits的值为true,就表示图片大小等于imageview的大小,不需要对图片进行放缩处理了。
代码块五:
       当mscaletype的类型为center时,实际是将图片进行移位操作,直接点说就是把图片的中心点移动到imageview的中心点,如果图片的宽高大于imageview的宽高此时只显示imageview所包含的部分,大于imageview的部分不再显示。
      【注意:center属性只对图片进行移动操作而不会进行放缩操作】。
代码块六:
        代码块六是当mscaletype==center_crop时,进行了一个条件判断:if(dwidth *vheight >vwidth *dheight),看到这句代码的时候我并没有理解其含义,然后我把这句代码转换了一下写法:if(dwidth / vwidth > dheight / vheight),通过这种转换写法然后再看就比较明白了,主要是用来判断宽高比的,就是说用来判断是图片的宽比较接近imageview控件的宽还是图片的高比较接近imageview控件的高。如果是图片的高比较接近imageview的高,通过计算获取需要放缩的scale的值,再计算出需要对图片的宽进行移动的值,最后通过对mdrawmatrix属性进行设置放缩和移动来达到控制图片进行放缩和移动的效果,同样的逻辑处理了当图片的宽比较接近imageview的宽的情况。从代码可以总结center_crop属性的特点是:对图片的宽高进行放缩处理,使一边达到imageview控件的宽高,另一边进行进行移动居中显示若超出则不再显示。
代码块七:
        代码块七是当mscaletype==center_inside时,首先判断图片宽高是否小于imageview宽高,如果图片宽高小于imageview的宽高,则scale=1.0f,也就是说不对图片进行放缩处理而是直接移动图片进行居中显示,否则通过math.min((float)vwidth / (float)dwidth, (float) vheight / (float)dheight);计算出需要对图片进行的放缩值,然后放缩图片宽高并对图片移动居中显示。从代码可以总结center_inside的特点是:控制图片尺寸,对图片宽高进行压缩处理,根据图片和控件的宽高比拿最大的一边进行压缩使之同控件一边相同,另一边小于控件。
代码块八:
        代码块八是对mscaletype为fit_center,fit_start,fit_end的情况下统一做了处理,先设置mtempsrc和mtempdst的边界后,通过调用mdrawmatrix的setrecttorect()方法来对图片进行放缩和移动操作,使图片最大边始终等于imageview相应的边。结合代码和代码测试结果可以得出如下结论:
        当图片的高大于宽时:
1.当mscaletype == fit_start时,对图片进行等比放缩,使图片的高与imageview的高相等,移动图片使之左对齐。
2.当mscaletype == fit_center时,对图片进行等比放缩,使图片的高与imageview的高相等,移动图片使之居中对齐。
3.当mscaletype == fit_end时,对图片进行等比放缩,使图片的高与imageview的高相等,移动图片使之右对齐。
        当图片的宽大于高时:
1.当mscaletype == fit_start时,对图片进行等比放缩,使图片的宽与imageview的宽相等,移动图片使之上对齐。
2.当mscaletype == fit_center时,对图片进行等比放缩,使图片的宽与imageview的宽相等,移动图片使之居中对齐。
3.当mscaletype == fit_end时,对图片进行等比放缩,使图片的宽与imageview的宽相等,移动图片使之下对齐。
        到这里mscaletype的8种用根据法算是分析完了,现在稍做总结:
fit_xy:对原图宽高进行放缩,该放缩不保持原比例来填充满imageview。
matrix:不改变原图大小从imageview的左上角开始绘制,超过imageview部分不再显示。
center:对原图居中显示,超过imageview部分不再显示。
center_crop:对原图居中显示后进行等比放缩处理,使原图最小边等于imageview的相应边。
center_inside:若原图宽高小于imageview宽高,这原图不做处理居中显示,否则按比例放缩原图宽(高)是之等于imageview的宽(高)。
fit_start:对原图按比例放缩使之等于imageview的宽高,若原图高大于宽则左对齐否则上对其。
fit_center:对原图按比例放缩使之等于imageview的宽高使之居中显示。
fit_end:对原图按比例放缩使之等于imageview的宽高,若原图高大于宽则右对齐否则下对其。
        还记得在博文开始的时候说到在imageview的构造方法中都调用了initimageview()方法么?他的源码如下:

private void initimageview() { 
 mmatrix = new matrix(); 
 mscaletype = scaletype.fit_center; 
} 

        可以看到,当我们没有在布局文件中使用scaletype属性或者是没有手动调用setscaletype方法时,那么mscaletype的默认值就是fit_center。
        好了,有关imageview的scaletype的讲解就算结束了,如有错误欢迎指正。以后如有其它属性需要详解,再做记录吧。

原文地址:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网