簡體   English   中英

放大圖像以填充 Android 中的整個 ImageView

[英]Scale an image up to fill entire ImageView in Android

我想將圖像放大以占據 ImageView 的整個大小。 這與使用scaleType=fit_center不同,因為如果圖像縱橫比與 ImageView 的縱橫比不完全匹配, fit_center會在圖像周圍留下條帶。 相反,我希望圖像居中並放大以完全填充封閉的視圖,並切掉任何多余的部分。

我可以通過在 onCreate() 期間計算我自己的自定義圖像矩陣來實現這一點:

final Display display = getWindowManager().getDefaultDisplay();
final float screenWidth = display.getWidth();
final float screenHeight = display.getHeight();
final float imageWidth = splashView.getDrawable().getIntrinsicWidth();
final float imageHeight = splashView.getDrawable().getIntrinsicHeight();
final Matrix splashMatrix = new Matrix();
final float scale = Math.max(screenHeight/imageHeight,screenWidth/imageWidth);
splashMatrix.postScale( scale, scale );
splashView.setImageMatrix(splashMatrix);

這很好用,但似乎必須有一個更容易的方法。 有誰知道在 ImageView 中放大圖像的方法,同時保留圖像的縱橫比並完全填充 ImageView?

(注意:在我的情況下,我的 ImageView 占據了全屏,所以我使用getWindowManager().getDisplay()來查找所需的圖像大小。你不能使用splashView.getWidth() / getHeight()因為視圖沒有'尚未布局,沒有尺寸)

您可以使用android:scaleType="centerCrop" 保持縱橫比並根據需要縮放圖像。

欲了解更多信息,請通過以下鏈接 go

http://developer.android.com/reference/android/widget/ImageView.html#attr_android:scaleType

在某些情況下,您只需要

android:adjustViewBounds="true"
imageView.setScaleType(ImageView.ScaleType.FIT_XY);

這對我來說可以使圖像適合整個圖像視圖,而且它說“ScaleType.FIT_XY”以適合 imageView 的 X 和 Y 軸是有道理的。

從 xml 文件中,它將是:

android:scaleType="fitXY"

我很晚了,但希望它對未來有所幫助。 這是我如何在沒有scaleType="fitXY"的情況下將圖像拉伸到全屏或圖像視圖的解決方案,因為它會損壞圖像。 使用以下庫。

[一個簡單的 imageview 以給定的比例縮放寬度或高度方面] https://github.com/santalu/aspect-ratio-imageview

要查找設備屏幕的縱橫比,請使用以下代碼。

DisplayMetrics metrics =this.getResources().getDisplayMetrics();
float ratio = ((float)metrics.heightPixels / (float)metrics.widthPixels);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM