获取imageview 图片大小
如题,ImageView在显示图片的时候,受限于屏幕大小,和图片宽高。通常图片是被缩放过,且不是宽和高都充满ImageView的。
此时,我们如何获得Image被实际绘制的宽高呢?如下:
- final ImageView iv = (ImageView) findViewById(R.id.iv_test);
- iv.setImageResource(R.drawable.abc);
- //等待ImageVivew加载完成
- iv.post(new Runnable(){
- @Override
- public void run() {
- // TODO Auto-generated method stub
- //ImageView的宽和高
- Log.d("lxy", "iv_W = " + iv.getWidth() + ", iv_H = " + iv.getHeight());
- //获得ImageView中Image的真实宽高,
- int dw = iv.getDrawable().getBounds().width();
- int dh = iv.getDrawable().getBounds().height();
- Log.d("lxy", "drawable_X = " + dw + ", drawable_Y = " + dh);
- //获得ImageView中Image的变换矩阵
- Matrix m = iv.getImageMatrix();
- float[] values = new float[10];
- m.getValues(values);
- //Image在绘制过程中的变换矩阵,从中获得x和y方向的缩放系数
- float sx = values[0];
- float sy = values[4];
- Log.d("lxy", "scale_X = " + sx + ", scale_Y = " + sy);
- //计算Image在屏幕上实际绘制的宽高
- int cw = (int)(dw * sx);
- int ch = (int)(dh * sy);
- Log.d("lxy", "caculate_W = " + cw + ", caculate_H = " + ch);
- }});
- <ImageView
- android:id="@+id/iv_test"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- />