获取imageview宽高
2022-12-28 本文已影响0人
Dapengyou
在开发中,可以通过两种方法来获得图片资源的真实宽高
- getDrawable().getBounds().height()
- getDrawable().getIntrinsicHeight()
由于 imageView 在不同的分辨率的屏幕中获取的宽高值是不准确的,所以需要根据 density 缩放 ,即 获取 imageview 宽高后,需要除以 density 来获取真实的宽高
float density = mContext.getResources().getDisplayMetrics().density;
int width = (int) (mImageView.getDrawable().getBounds().width() / density); //单位是dp
int height = (int) (mImageView.getDrawable().getBounds().height() / density); //单位是dp
float density = mContext.getResources().getDisplayMetrics().density;
int width = (int) (mSureView.getDrawable().getIntrinsicWidth() / density); //单位是dp
int height = (int) (mImageView.getDrawable().getIntrinsicHeight() / density); //单位是dp
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:src="@drawable/ic_launcher" />
</LinearLayout>
小 tip:
如果在自定义 view 中,可以使用:
- getHeight(): 获取整个View的高度。
- getMeasuredHeight(): 在父布局的onLayout()方法或者此View的onDraw()方法调用