1.setImageResource():
/**
* Sets a drawable as the content of this ImageView.
*
* <p class="note">This does Bitmap reading and decoding on the UI
* thread, which can cause a latency hiccup. If that's a concern,
* consider using {@link #setImageDrawable(android.graphics.drawable.Drawable)} or
* {@link #setImageBitmap(android.graphics.Bitmap)} and
* {@link android.graphics.BitmapFactory} instead.</p>
*
* @param resId the resource identifier of the drawable
*
* @attr ref android.R.styleable#ImageView_src
*/
@android.view.RemotableViewMethod
public void setImageResource(@DrawableRes int resId) {
// The resource configuration may have changed, so we should always
// try to load the resource even if the resId hasn't changed.
final int oldWidth = mDrawableWidth;
final int oldHeight = mDrawableHeight;
updateDrawable(null);
mResource = resId;
mUri = null;
resolveUri();
if (oldWidth != mDrawableWidth || oldHeight != mDrawableHeight) {
requestLayout();
}
invalidate();
}
根据注释可以知道这个方法是在UI线程中对图片读取和解析的,所以有可能对一个Activity的启动造成延迟。所以如果顾虑到这个,建议使用setImageDrawable()和setImageBitmap()来代替它。
2.setImageBitmap():
/**
* Sets a Bitmap as the content of this ImageView.
*
* @param bm The bitmap to set
*/
@android.view.RemotableViewMethod
public void setImageBitmap(Bitmap bm) {
// Hacky fix to force setImageDrawable to do a full setImageDrawable
// instead of doing an object reference comparison
mDrawable = null;
if (mRecycleableBitmapDrawable == null) {
mRecycleableBitmapDrawable = new ImageViewBitmapDrawable(
mContext.getResources(), bm);
} else {
mRecycleableBitmapDrawable.setBitmap(bm);
}
setImageDrawable(mRecycleableBitmapDrawable);
}
从以上代码可以看出实际上setImageBitmap()做的事情就是把Bitmap对象封装成Drawable对象,然后调用setImageDrawable()来设置图片。
3.setImageDrawable():
/**
* Sets a drawable as the content of this ImageView.
*
* @param drawable the Drawable to set, or {@code null} to clear the
* content
*/
public void setImageDrawable(@Nullable 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();
}
}
Bitmap和Drawable的区别:可以简单地理解为Bitmap储存的是像素信息,Drawable储存的是对Canvas的一系列操作。可以参考文章Bitmap和Drawable的区别,为什么要用bitmap?
总结一下:
setImageResource()简单,会根据设备分辨率进行图片大小缩放适配,但是占空间,资源不会及时回收,图片多且大时运行很容易出OOM。
setImageBitmap()比较麻烦,要手动设置参数,不过比较安全。