ImageView是android中控件使用频繁的控件之一。解读源码,有助于解答一些常见的问题,如TextView设置的左边图时drawable为什么要setBound。
我们都知道自定义view一般需实现两个方法:onMeasure()和onDraw()方法。所以我们从这两个方面解读。
1. onMeasure()
首先上源码:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
resolveUri();
int w;
int h;
// Desired aspect ratio of the view's contents (not including padding)
float desiredAspect = 0.0f;
// We are allowed to change the view's width
boolean resizeWidth = false;
// We are allowed to change the view's height
boolean resizeHeight = false;
final int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
final int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
if (mDrawable == null) {
// If no drawable, its intrinsic size is 0.
mDrawableWidth = -1;
mDrawableHeight = -1;
w = h = 0;
} else {
w = mDrawableWidth;
h = mDrawableHeight;
if (w <= 0) w = 1;
if (h <= 0) h = 1;
// We are supposed to adjust view bounds to match the aspect
// ratio of our drawable. See if that is possible.
if (mAdjustViewBounds) {
resizeWidth = widthSpecMode != MeasureSpec.EXACTLY;
resizeHeight = heightSpecMode != MeasureSpec.EXACTLY;
desiredAspect = (float) w / (float) h;
}
}
int pleft = mPaddingLeft;
int pright = mPaddingRight;
int ptop = mPaddingTop;
int pbottom = mPaddingBottom;
int widthSize;
int heightSize;
if (resizeWidth || resizeHeight) {
/* If we get here, it means we want to resize to match the
drawables aspect ratio, and we have the freedom to change at
least one dimension.
*/
// Get the max possible width given our constraints
widthSize = resolveAdjustedSize(w + pleft + pright, mMaxWidth, widthMeasureSpec);
// Get the max possible height given our constraints
heightSize = resolveAdjustedSize(h + ptop + pbottom, mMaxHeight, heightMeasureSpec);
if (desiredAspect != 0.0f) {
// See what our actual aspect ratio is
float actualAspect = (float)(widthSize - pleft - pright) /
(heightSize - ptop - pbottom);
if (Math.abs(actualAspect - desiredAspect) > 0.0000001) {
boolean done = false;
// Try adjusting width to be proportional to height
if (resizeWidth) {
int newWidth = (int)(desiredAspect * (heightSize - ptop - pbottom)) +
pleft + pright;
if (newWidth <= widthSize) {
widthSize = newWidth;
done = true;
}
}
// Try adjusting height to be proportional to width
if (!done && resizeHeight) {
int newHeight = (int)((widthSize - pleft - pright) / desiredAspect) +
ptop + pbottom;
if (newHeight <= heightSize) {
heightSize = newHeight;
}
}
}
}
} else {
/* We are either don't want to preserve the drawables aspect ratio,
or we are not allowed to change view dimensions. Just measure in
the normal way.
*/
w += pleft + pright;
h += ptop + pbottom;
w = Math.max(w, getSuggestedMinimumWidth());
h = Math.max(h, getSuggestedMinimumHeight());
widthSize = resolveSizeAndState(w, widthMeasureSpec, 0);
heightSize = resolveSizeAndState(h, heightMeasureSpec, 0);
}
setMeasuredDimension(widthSize, heightSize);
}
第25、26行w、h被赋值成图片的宽高。第94、95行w和h分别加上各自方向上的内边距。 resolveSizeAndState()方法用来处理出imageview的大小。其首先会获得本view所在容器类(viewgroup的子类)传给本view的measureSpec中的大小和模式。如果是MeasureSpec.UNSPECIFIED,则代表本view想要多大就多大;如果是MeasureSpec.EXACTLY则本view的大小为measureSpec中的大小;如果是MeasureSpec.AT_MOST,则比较measureSpec中的大小和本view的内容大小,取小值。具体请阅读resolveSizeAndState方法源码。
最后一句设置了ImageView的大小。
到这里,我们自然而然对onMeasure()有疑问,该方法的两个参数值是从哪来的。上面说过是从view所在容器类传过来的。我们就拿FrameLayout的onMeasure()为例说明。
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int count = getChildCount();
final boolean measureMatchParentChildren =
MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY ||
MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
mMatchParentChildren.clear();
int maxHeight = 0;
int maxWidth = 0;
int childState = 0;
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (mMeasureAllChildren || child.getVisibility() != GONE) {
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
maxWidth = Math.max(maxWidth,
child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
maxHeight = Math.max(maxHeight,
child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
childState = combineMeasuredStates(childState, child.getMeasuredState());
if (measureMatchParentChildren) {
if (lp.width == LayoutParams.MATCH_PARENT ||
lp.height == LayoutParams.MATCH_PARENT) {
mMatchParentChildren.add(child);
}
}
}
}
// Account for padding too
maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();
maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();
// Check against our minimum height and width
maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
// Check against our foreground's minimum height and width
final Drawable drawable = getForeground();
if (drawable != null) {
maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
}
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
resolveSizeAndState(maxHeight, heightMeasureSpec,
childState << MEASURED_HEIGHT_STATE_SHIFT));
count = mMatchParentChildren.size();
if (count > 1) {
for (int i = 0; i < count; i++) {
final View child = mMatchParentChildren.get(i);
final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
final int childWidthMeasureSpec;
if (lp.width == LayoutParams.MATCH_PARENT) {
final int width = Math.max(0, getMeasuredWidth()
- getPaddingLeftWithForeground() - getPaddingRightWithForeground()
- lp.leftMargin - lp.rightMargin);
childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
width, MeasureSpec.EXACTLY);
} else {
childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
getPaddingLeftWithForeground() + getPaddingRightWithForeground() +
lp.leftMargin + lp.rightMargin,
lp.width);
}
final int childHeightMeasureSpec;
if (lp.height == LayoutParams.MATCH_PARENT) {
final int height = Math.max(0, getMeasuredHeight()
- getPaddingTopWithForeground() - getPaddingBottomWithForeground()
- lp.topMargin - lp.bottomMargin);
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
height, MeasureSpec.EXACTLY);
} else {
childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
getPaddingTopWithForeground() + getPaddingBottomWithForeground() +
lp.topMargin + lp.bottomMargin,
lp.height);
}
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
}
}
其中measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0)为关键代码。这个方法会根据容器类的剩余空间和view的LayoutParam来生成MeasureSpec,然后调用view的measure(int widthMeasureSpec, int heightMeasureSpec)方法。measure(int widthMeasureSpec, int heightMeasureSpec)方法中又调用了onMeasure(widthMeasureSpec, heightMeasureSpec)方法。故onMeasure(widthMeasureSpec, heightMeasureSpec)中的MeasureSpec是从容器类通过一系列计算后传过来的。
在FrameLayout的onMeasure()方法中发现最后一行调用了一次view的onMeasure方法,而measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0) 调用过一次view的onMeasure方法,所以我们经常看到自定义view的onMeasure方法至少调用两次就是这个原因。
2. onDraw()
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mDrawable == null) {
return; // couldn't resolve the URI
}
if (mDrawableWidth == 0 || mDrawableHeight == 0) {
return; // nothing to draw (empty bounds)
}
if (mDrawMatrix == null && mPaddingTop == 0 && mPaddingLeft == 0) {
mDrawable.draw(canvas);
} else {
int saveCount = canvas.getSaveCount();
canvas.save();
if (mCropToPadding) {
final int scrollX = mScrollX;
final int scrollY = mScrollY;
canvas.clipRect(scrollX + mPaddingLeft, scrollY + mPaddingTop,
scrollX + mRight - mLeft - mPaddingRight,
scrollY + mBottom - mTop - mPaddingBottom);
}
canvas.translate(mPaddingLeft, mPaddingTop);
if (mDrawMatrix != null) {
canvas.concat(mDrawMatrix);
}
mDrawable.draw(canvas);
canvas.restoreToCount(saveCount);
}
}
第26行canvas先平移内边距,29行对canvas执行矩阵变化,31行画图片。这里的mDrawMatrix 在下段内容介绍。
3. setImageDrawable方法
public void setImageDrawable(Drawable drawable) {
if (mDrawable != drawable) {
mResource = 0;
mUri = null;
final int oldWidth = mDrawableWidth;
final int oldHeight = mDrawableHeight;
updateDrawable(drawable);
if (oldWidth != mDrawableWidth || oldHeight != mDrawableHeight) {
requestLayout();
}
invalidate();
}
}
第9行updateDrawable(drawable)从方法名上我们知道是更新drawable,其中调用了configureBounds()方法,从方法名上看是配置边界的意思,该方法源码:
private void configureBounds() {
if (mDrawable == null || !mHaveFrame) {
return;
}
//从drawable的getIntrinsicWidth()方法的说明可知,
// return -1 if it has no intrinsic width, such as with a solid color(一个填充颜色的shape是没有固定的宽的)
int dwidth = mDrawableWidth; //图片的宽。mDrawable为空,则mDrawableWidth为-1,也可能是getIntrinsicWidth()得到的-1
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.
如果没有固定宽高,或者缩放类型是FIT_XY,则设置mDrawable的边界为Imageview的宽高
*/
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的边界设为其自身的宽高
mDrawable.setBounds(0, 0, dwidth, dheight);
if (ScaleType.MATRIX == mScaleType) {
// Use the specified matrix as-is.
if (mMatrix.isIdentity()) {
mDrawMatrix = null;
} else {
mDrawMatrix = mMatrix; //将用setImageMatrix方法设置的mMatrix赋值给mDrawMatrix
}
} else if (fits) {
// The bitmap fits exactly, no transform needed.不需要转换
mDrawMatrix = null;
} else if (ScaleType.CENTER == mScaleType) {
// Center bitmap in view, no scaling.
//ScaleType.CENTER 把图片居中显示,只平移到中间
mDrawMatrix = mMatrix;
mDrawMatrix.setTranslate((int) ((vwidth - dwidth) * 0.5f + 0.5f),
(int) ((vheight - dheight) * 0.5f + 0.5f));
} else if (ScaleType.CENTER_CROP == mScaleType) {//ScaleType.CENTER_CROP 按宽高中的最大缩放值缩放,然后居中显示
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) {//ScaleType.CENTER_INSIDE 按宽高中的最小缩放值缩放,然后居中显示
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;
/**
* public boolean setRectToRect(RectF src,RectF dst, Matrix.ScaleToFit stf)
* 将当前matrix的值设置为这样的值,对src进行变换后可以得到dst,因两者都是RectF,所以该matrix的值只能是伸缩和平移的组合,
* 设置成功了返回true,stf为伸缩参数,这个Matrix.ScaleToFit伸缩参数有什么名堂呢,它有四个常量,
* 每个常量应用后会导致matrix有什么结果呢,根据那4个常量的文字说明可知,CENTER,END,START表示得到的伸缩矩阵m,
* m对src进行变换后得到dst1,dst1跟src有同样的宽高比例,dst1在dst的内部,不同的地方是
* CENTER的状态是这样的:dst1.left-dst.left=dst.right-dst1.right,dst1.top-dst.top=dst.bottom-dst1.bottom;
* END的状态是这样的:dst1.right=dst.right,dst1.bottom=dst.bottom.
* START的状态是这样的:dst1.left=dst.left,dst1.top=dst.top;
* 至于FILL表示得到的伸缩矩阵m,通过它对src变换后得到的Rect就是dst,完全重合。结论通过RectF(0,0,10,10), RectF(0,0,20,30)这两个矩阵得到了验证。
*/
mDrawMatrix.setRectToRect(mTempSrc, mTempDst, scaleTypeToScaleToFit(mScaleType));
}
}
}
从drawable的getIntrinsicWidth()方法的说明可知,-1 if it has no intrinsic width, such as with a solid color(一个填充颜色的shape是没有固定的宽的)。这个方法中drawable调用了setBound方法,这就解释了ImageView设置drawable时,drawable不需setBound的,而TextView设置的leftDrawable需setBound。
其他,setFrame方法在view的layout方法中被调用,其用来分配view的大小和位置。
ImageView还有很多的知识点,大家多看看源码,今天就讲解到这里了。