Android之获取加载图片宽高问题(getIntrinsicWidth与getwidth的区别)
16lz
2022-03-08
获取图片大小:在Android的开发中,凡是需要画图的地方大都离不开类Drawable。
//方法1 获取宽高int width1 = imgDetailImage.getDrawable().getBounds().width();int height1 = imgDetailImage.getDrawable().getBounds().height();//方法2 获取宽高float width = imgDetailImage.getDrawable().getIntrinsicWidth();float height = imgDetailImage.getDrawable().getIntrinsicHeight();
方法1:
如果我们想直接在onCreat()方法中获取会发现方法1获取到的宽高为0,为什么呢?
因为当一个view对象创建时,android并不知道其大小,所以getWidth()和 getHeight()返回的结果是0,真正大小是在计算布局时才会计算,所以会发现一个有趣的事,即在onDraw( ) 却能取得长宽的原因。
/** * @return the rectangle's width. This does not check for a valid rectangle * (i.e. left <= right) so the result may be negative. * 矩形的宽度。这并不检查有效的矩形(即左 =右)结果可能是负面的 */ public final int width() { return right - left; } /** * @return the rectangle's height. This does not check for a valid rectangle * (i.e. top <= bottom) so the result may be negative. * 矩形的高度。这并不检查有效的矩形(即左 =右)结果可能是负面的 */ public final int height() { return bottom - top; }
方法2:
/** * Return the intrinsic width of the underlying drawable object. Returns * -1 if it has no intrinsic width, such as with a solid color. */ public int getIntrinsicWidth() { return -1; } /** * Return the intrinsic height of the underlying drawable object. Returns * -1 if it has no intrinsic height, such as with a solid color. */ public int getIntrinsicHeight() { return -1; }
对View上的内容进行测量后得到的View内容占据的高度,前提是你必须在父布局的onLayout()方法或者此View的onDraw()方法调调 用measure(0,0);(measure 参数的值你可以自己定义),否则你得到的结果和getHeight()得到的结果一样。
有时候通过这这种方法取到的宽和高和实际的并不一样,这是怎么回事呢?
测试发现:测试设备dpi是320,而android为了让同一个view在不同dpi的设备上大小尽量保持一致,建议度量单位采用dip/dp。所以我猜测上面两个方法的单位应该是dp,所以807px = 807 * 160 / 320 = 403.5 = 404dp ; 1211px = 1211 * 160 / 320 = 605.5 = 606dp。
所以正确理解应该是:得到的非图片固有属性,而是与设备相关的值。
注:就针对获取宽高为0的,建议使用第二种。
更多相关文章
- Android中获取当前屏幕的尺寸大小
- Android中打开新的Activity的三种方法
- android中常见的错误及解决办法
- Android(安卓)远程链接 daemon not running 解决方法
- android从服务器下载文件(php+apache+win7+MySql)
- 【解决方法】ADT在线安装
- 浅谈Java中Collections.sort对List排序的两种方法
- Python list sort方法的具体使用
- python list.sort()根据多个关键字排序的方法实现