Github項目地址:
https://github.com/SherlockShi/AspectRatioImageView
一、前言
在項目開發過程中,經常會有這樣的情況:美工MM切好一張圖,個人信息界面頂部的背景,美美的,但是要求寬高比例一定要5:3,不然圖片會變形。好,說干就干。
width肯定是要match_parent了,圖片寬度才能與屏幕寬度一致,但是高度呢?wrap_content?那肯定不行,圖片肯定變形了。某個固定的高度值呢?那也不行。
如此,便有了這個方便的自定義View - AspectRatioImageView
,簡單得只需要像普通的ImageView一樣使用,再配置一定的寬度比例值
、高度比例值
,就可輕松實現上面的需求了。
二、一言不合就上圖
AspectRatioImageView
三、使用方法
依賴
使用Gradle依賴:
dependencies {
...
compile 'com.sherlockshi.widget:aspectratioimageview:1.0.1'
}
或使用Maven依賴:
<dependency>
<groupId>com.sherlockshi.widget</groupId>
<artifactId>aspectratioimageview</artifactId>
<version>1.0.1</version>
<type>pom</type>
</dependency>
用法
像使用ImageView一樣,在XML文件中使用:
<com.sherlockshi.widget.AspectRatioImageView
android:layout_width="match_parent"
android:layout_height="0dp"
android:scaleType="centerCrop"
app:width_ratio="4"
app:height_ratio="2"
android:src="..."/>
屬性
AspectRatioImageView有以下兩個屬性:
width_ratio
: 寬度比例值,類型為integer
height_ratio
: 高度比例值,類型為integer
以上兩個屬性,只要有一個屬性未設置,就會使用默認比例3:2.
以上,你就可以和美工MM愉快地出去喝一杯了,不不,你就可以輕松實現項目需求了。
PS:歡迎關注SherlockShi博客