Android中ImageView.src設置圖片拉伸、填滿控件的方法
問題
ImageView.src設置圖片資源,圖片不拉伸了,卻有空隙部分:
<LinearLayout android:id="@+id/linearLayout1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" > <ImageView android:layout_width="wrap_content" android:layout_height="205dp" android:scaleType="centerInside" android:background="@drawable/feature_guide_1" > </ImageView> </LinearLayout>
解決
如下方式設置 就沒有空隙了
<LinearLayout android:id="@+id/linearLayout1" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:adjustViewBounds="true" android:scaleType="fitXY" android:src="@drawable/feature_guide_0" > </ImageView> </LinearLayout>
以下為參考內(nèi)容:
最近碰到一個需求,要求是在不知道圖片寬度和高度的情況下,讓圖片在指定寬度內(nèi)充滿,同時高度自適應,在網(wǎng)絡上查找了一下,也有很多解決方法,后來針對自己的應用,選擇了一個修改較小的方案,最后證明效果還是蠻不錯的,記錄在這里,希望能幫助到有同樣需求的人。
好了,言歸正傳
首先,需要給你的ImageView布局加上Android:adjustViewBounds="true"
<ImageView android:id="@+id/test_image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:scaleType="fitXY" android:adjustViewBounds="true" android:layout_gravity="center" android:contentDescription="@string/app_name" android:src="@drawable/ic_launcher" />
然后,在代碼里設置ImageView.最大寬度和最大高度,因為adjustViewBounds
屬性只有在設置了最大高度和最大寬度后才會起作用
int screenWidth = getScreenWidth(this); ViewGroup.LayoutParams lp = testImage.getLayoutParams(); lp.width = screenWidth; lp.height = LayoutParams.WRAP_CONTENT; testImage.setLayoutParams(lp); testImage.setMaxWidth(screenWidth); testImage.setMaxHeight(screenWidth * 5);
這里其實可以根據(jù)需求而定,我這里測試為最大寬度的5倍
ok,接下來,再按照常規(guī)方法加載圖片就會得倒預期的效果了,需要的同學可以試試,good luck.
總結
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關文章
Android studio 解決logcat無過濾工具欄的操作
這篇文章主要介紹了Android studio 解決logcat無過濾工具欄的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04Android中使用Handler及Countdowntimer實現(xiàn)包含倒計時的閃屏頁面
這篇文章主要介紹了Android中使用Handler及Countdowntimer實現(xiàn)包含倒計時的閃屏頁面,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-03-03Android開發(fā)之sqlite3命令行簡單使用方法
這篇文章主要介紹了Android開發(fā)之sqlite3命令行簡單使用方法,分析了Android增刪改查等常用sqlite3的數(shù)據(jù)庫操作命令使用方法,需要的朋友可以參考下2016-02-02Android自定義view利用PathEffect實現(xiàn)動態(tài)效果
這篇文章主要為大家詳細介紹了Android自定義view利用PathEffect實現(xiàn)動態(tài)效果,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-05-05