首页 > 代码库 > android ImageView setImageDrawable 和 setImageResource 的区别

android ImageView setImageDrawable 和 setImageResource 的区别

1. setImageResource是同步的,资源图片的读取和解码都是在主线程中进行的。setImageDrawable是异步的。

2. 加载速度的区别。setImageResource要快于setImageDrawable和setImageBitmap.

/**     * 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(int resId) {        if (mUri != null || mResource != resId) {            final int oldWidth = mDrawableWidth;            final int oldHeight = mDrawableHeight;            updateDrawable(null);            mResource = resId;            mUri = null;            resolveUri();            if (oldWidth != mDrawableWidth || oldHeight != mDrawableHeight) {                requestLayout();            }            invalidate();        }    }

 

 /**     * 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;            final int oldWidth = mDrawableWidth;            final int oldHeight = mDrawableHeight;            updateDrawable(drawable);            if (oldWidth != mDrawableWidth || oldHeight != mDrawableHeight) {                requestLayout();            }            invalidate();        }    }

 

/**     * Sets a Bitmap as the content of this ImageView.     *      * @param bm The bitmap to set     */    @android.view.RemotableViewMethod    public void setImageBitmap(Bitmap bm) {        // if this is used frequently, may handle bitmaps explicitly        // to reduce the intermediate drawable object        setImageDrawable(new BitmapDrawable(mContext.getResources(), bm));    }

 

android ImageView setImageDrawable 和 setImageResource 的区别