wordpress站长统计,青岛做公司网站的公司,wordpress 首页 摘要,龙海市住房和城乡建设局网站在 Android 开发中#xff0c;ImageView 是一个用户界面控件#xff0c;用于在应用中显示图片。它是 Android UI 组件库中一个非常基础和常用的部分。使用 ImageView#xff0c;你可以在屏幕上显示来自不同来源的图像#xff0c;比如位图文件、绘图资源 drawable、网络来源…在 Android 开发中ImageView 是一个用户界面控件用于在应用中显示图片。它是 Android UI 组件库中一个非常基础和常用的部分。使用 ImageView你可以在屏幕上显示来自不同来源的图像比如位图文件、绘图资源 drawable、网络来源或者相机拍摄的图片。
在实际的开发过程中我们会在 Java 或 Kotlin 代码中调用 setImageResource()、setImageBitmap()、setImageDrawable() 等方法来设置或改变图片。
但我最近在检测应用的性能时发现 imageView 在加载图片竟有一些耗时于是进入源码来看看这几个给 imageView 设置图片的方法都有什么区别 imageView.setImageResource() public void setImageResource(DrawableRes int resId) {final int oldWidth mDrawableWidth;final int oldHeight mDrawableHeight;updateDrawable(null);mResource resId;mUri null;resolveUri();if (oldWidth ! mDrawableWidth || oldHeight ! mDrawableHeight) {requestLayout();}invalidate();}
在 setImageResource 方法中首先 updateDrawable() 做了重置操作后面给成员变量 mResource 赋值接着执行 resolveUri() 这个方法对 mResource 进行解析 private void resolveUri() {Drawable d null;if (mResource ! 0) {try {// 根据传进来的资源ID去获取对应的Drawable耗时d mContext.getDrawable(mResource); } catch (Exception e) {// Dont try again.mResource 0;}} else if (mUri ! null) {d getDrawableFromUri(mUri);if (d null) {// Dont try again.mUri null;}} else {return;}updateDrawable(d);}
resolveUri() 方法中会将刚刚传进来的 mResource 去获取对应的 Drawable获取到 Drawble 后通过调用 updateDrawable() 来更新 imageView 中的图像 imageView.setImageBitmap() public void setImageBitmap(Bitmap bm) {mDrawable null;if (mRecycleableBitmapDrawable null) {mRecycleableBitmapDrawable new BitmapDrawable(mContext.getResources(), bm);} else {mRecycleableBitmapDrawable.setBitmap(bm);}setImageDrawable(mRecycleableBitmapDrawable);}
setImageBitmap 代码非常少首先确定有一个 BitmapDrawable 对象将传进来的 Bitmap 赋值于此然后调用 setImageDrawable() 方法 imageView.setImageDrawable() 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();}}
在 setImageDrawable 方法中直接将传进来的 Drawable 来调用 updateDrawable() 方法来更新imageView() 中的图像 总结 用这三种方法去更新 imageView 最终都会调用到 updateDrawable() 这个方法但是在 setImageResource() 中的 resolveUri() 方法涉及到了资源获取mContext.getDrawable()这个是耗时的所以在短时间内调用大量的 setImageResource 可能会造成应用卡顿。
解决方法将资源 ID 获取到的 Drawable 进行缓存或者设置为成员变量再调用 setImageDrawable() 即可。这样子能避免资源获取而造成的卡顿。 此外ImageView 还提供了其他方法如 setImageURI(Uri uri)用于通过 URI 设置图像但无论哪种设置图像的方法最终都是通过 Drawable 来实现图像的渲染。所以在短时间内大量设置imageView 图像时需要优先缓存 Drawable 来加载图像来保证性能是最佳的