編輯:Android 開發實例
ImageView 用來顯示任意圖像(例如圖示),可從資源或圖片來源載入,並提供縮放、著色等顯示選項。它同時也是 ImageButton 與 QuickContactBadge 的父類。
public class ImageView extends View
繼承鏈:Object → View → ImageView
已知直接子類:ImageButton、QuickContactBadge;已知間接子類:ZoomButton
android:adjustViewBounds:是否保持圖片長寬比。單獨設定沒有效果,必須與 maxWidth/maxHeight 一起使用。android:maxWidth / android:maxHeight:設定 View 的最大寬/高,單獨使用無效,需搭配 adjustViewBounds。若想「限制大小又保持比例」,三步驟:把 adjustViewBounds 設為 true、設定 maxWidth/maxHeight、並把 layout_width 與 layout_height 設為 wrap_content。android:cropToPadding:是否把超出 padding 的區域裁掉。需與 android:scrollY(或 scrollX)搭配才看得到效果:圖片被捲動後,超出 padding 的部分會被裁切呈現空白。android:src:設定要顯示的 Drawable(圖片,也可以是顏色,但必須指定 View 尺寸)。android:tint:把圖片整體渲染成指定顏色,常用來讓同一張圖變化出不同色調。| 值 | 名稱 | 行為 |
|---|---|---|
| 0 | matrix | 用矩陣繪圖,完全自訂。 |
| 1 | fitXY | 不按比例拉伸,填滿 View 的寬高。 |
| 2 | fitStart | 按比例縮放後靠左對齊(左上)。 |
| 3 | fitCenter | 按比例縮放後置中。 |
| 4 | fitEnd | 按比例縮放後靠右對齊(右下)。 |
| 5 | center | 以原尺寸居中顯示;圖片大於 View 時只顯示中央部分。 |
| 6 | centerCrop | 按比例放大直到填滿某邊,超出部分裁掉。 |
| 7 | centerInside | 原圖較小時原尺寸居中;較大時縮至 View 大小後居中。 |
實務上最常用的是 fitCenter(完整顯示、不裁切)與 centerCrop(填滿、可裁切)這兩種。
<ImageView android:background="@android:color/white"
android:src="@drawable/btn_mode_switch_bg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></ImageView>
<ImageView android:layout_marginLeft="5dp"
android:background="@android:color/white"
android:tint="#ffff00"
android:src="@drawable/btn_mode_switch_bg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></ImageView>
兩張圖使用同一張原圖,右邊因為加了 tint 而整體變黃。
<ImageView android:background="@android:color/white"
android:scrollY="-10px" android:cropToPadding="true"
android:src="@drawable/btn_mode_switch_bg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></ImageView>
<ImageView android:background="@android:color/white"
android:scrollY="10px" android:cropToPadding="true"
android:src="@drawable/btn_mode_switch_bg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></ImageView>
<ImageView android:paddingTop="10px"
android:background="@android:color/white"
android:scrollY="10px" android:cropToPadding="false"
android:src="@drawable/btn_mode_switch_bg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></ImageView>
把 cropToPadding 在 true 與 false 之間切換,並搭配 padding 與 scrollY 的正負值,就能看出裁切行為的差異。
這幾個屬性裡,android:tint 最容易上手;adjustViewBounds 與 cropToPadding 則是名不副實的難點——兩者都必須搭配其他屬性才會生效,單獨寫上去不會有任何變化,實測時要花一點時間才能看出規律。
資料來源:Android 官方 API 文件整理(Android 2.2 r1)。
Android 自訂 EditText 與 AutoCompleteTextView 的文字選取底色
多數 Android ROM 上,文字被選取時的背景色是清爽的鮮綠色,視覺上不難看。但某些三星機型卻是藍色,和整體介面放在一起格外突兀。好消息是,這個顏色完全可以透過程式
MediaPlayer 播放網路音訊:進度條同步與緩衝處理
前面談過 MediaPlayer 的基本用法,這次深入探討線上播放。由於線上影片比線上音訊複雜得多(協定、緩衝策略、畫面同步都要處理),本文先從音訊下手,把基礎打穩之後再
Android 圖片縮放與旋轉:Matrix 的靜態與動態兩種玩法
Matrix 是 Android 做圖形變形的基礎工具,縮放與旋轉都只是它的其中兩個方法。本文用兩個層次不同的範例來說明:先做一次性變形,再做可依輸入即時調整的動態版本。
仿 QQ 空間底部中央加號選單:Android 完整實作解析
網路上搜得到的「仿 QQ 空間底部選單」範例不少,但仔細看會發現很多問題:布局裡塞滿了寫死的魔法數字、不同解析度下位置就歪掉、PopupWindow 的生命週期也沒處理好