系列文章目录
Android中ImageView中无法直接包裹图片
前言
今天有个以前学校的学弟使用ImageView加载图片时出现了布局空间多余的问题(想动态适配图片的大小),如下图所示。
一、先看下XML文件代码
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/xxxx" />
</RelativeLayout>
二、解决思路
1.没看到代码时的思路
动态获取屏幕宽高,然后设置到图片中。
例:
DisplayMetrics outMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
int wPixels = outMetrics.widthPixels;
int hPixels = outMetrics.heightPixels;
Log.i(TAG, "wPixels = " + widthPixels + ",hPixels = " + heightPixels);
问题得以解决,但是感觉比较麻烦
2.看到代码后的思路
如果学过Android自定义view的朋友应该很快就能确定是设置为wrap_content的问题。先查看下源码。adjustViewBounds能解决这一问题。
* @param adjustViewBounds Whether to adjust the bounds of this view
* to preserve the original aspect ratio of the drawable. 调整此视图的边界以保持绘图的原始宽高比。
*
* @see #getAdjustViewBounds()
*
* @attr ref android.R.styleable#ImageView_adjustViewBounds
*/
@android.view.RemotableViewMethod
public void setAdjustViewBounds(boolean adjustViewBounds) {
mAdjustViewBounds = adjustViewBounds;
if (adjustViewBounds) {
setScaleType(ScaleType.FIT_CENTER);
}
}
且其初始默认值为false
setAdjustViewBounds(a.getBoolean(R.styleable.ImageView_adjustViewBounds, false));
简单的查看一下Android官方文档也发现了此属性。
三、解决(时间紧请直接跳转至此)
调用adjustViewBounds,并设置为true即可。
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/xxxx"
android:adjustViewBounds="true" />
希望能解决你的问题。