[英]Scale Image in ImageView to Height, maintaining aspect ratio outside bounds of screen, and align right
[英]Fill ImageView to screen whilst maintaining aspect ratio
我有兩個圖像文件:
我已將每個圖像分別放在項目的xhdpi和xxhdpi drawables文件夾中。 我正在嘗試使兩個圖像均能適當縮放並填充屏幕而沒有任何空白。
我的XML代碼如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.vax.gamurs.LandingPage"
android:background="#ffffffff"
android:orientation="vertical"
>
<ImageView
android:id="@+id/LandingBack"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/background"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
我在Nexus 4和Nexus 5的兩側都出現了空白。如何在保持寬高比的同時消除空白並讓圖像充滿屏幕?
使用scaleType="centerCrop"
如下:
<ImageView
android:id="@+id/LandingBack"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/background"
android:scaleType="centerCrop"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
上面的方法將裁剪圖像。 不幸的是,如果您使用固定大小的可繪制對象並希望支持不同的屏幕大小,則這是一個缺點。
另一種方法是使用如下圖所示的9補丁圖像。 這將拉伸藍色背景以填充空白區域。
下載9Patch圖片的鏈接: https ://dl.dropboxusercontent.com/u/2411239/sampleimg.9.png
這是一個示例屏幕截圖,顯示了它如何工作:
更新:
您的新ImageView
應該如下所示:
<ImageView
android:id="@+id/LandingBack"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/sampleimg"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
同樣作為參考,我使用1px拉伸補丁,如下圖所示:
您不能在保持寬高比的同時進行填充,因為這沒有意義。 您可以將背景設置為與藍色相同。 (非常簡單),或者使用簡單的數學方法僅使圖像填充高度或寬度
w = W; h =(w / W)H;
其中W是屏幕的寬度,H是屏幕的高度,w是圖像的寬度,h是圖像的高度
將寬度與高度互換以填充整個高度而不是寬度
嘗試像這樣設置imageview的背景:
android:background="@drawable/background"
而不是“ src”。 如果使用src,則圖像不會縮放,但是背景會縮放。
但是這種縮放會破壞您的圖像,您應該使用九補丁。
只需使用Imageview的屬性
android:scaleType="fitXY"
那意味着
<ImageView
android:scaleType="fitXY"
android:id="@+id/LandingBack"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/background"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
在Imageview中完成操作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.