Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 2.2 API 中文(6):ImageView 屬性全解析

編輯:Android 開發實例

ImageView 用來顯示任意圖像(例如圖示),可從資源或圖片來源載入,並提供縮放、著色等顯示選項。它同時也是 ImageButton 與 QuickContactBadge 的父類。

類別結構

public class ImageView extends View

繼承鏈:Object → View → ImageView

已知直接子類:ImageButton、QuickContactBadge;已知間接子類:ZoomButton

XML 屬性

  • 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:把圖片整體渲染成指定顏色,常用來讓同一張圖變化出不同色調。

scaleType 的八種填充模式

值名稱行為
0matrix用矩陣繪圖,完全自訂。
1fitXY不按比例拉伸,填滿 View 的寬高。
2fitStart按比例縮放後靠左對齊(左上)。
3fitCenter按比例縮放後置中。
4fitEnd按比例縮放後靠右對齊(右下)。
5center以原尺寸居中顯示;圖片大於 View 時只顯示中央部分。
6centerCrop按比例放大直到填滿某邊,超出部分裁掉。
7centerInside原圖較小時原尺寸居中;較大時縮至 View 大小後居中。

實務上最常用的是 fitCenter(完整顯示、不裁切)與 centerCrop(填滿、可裁切)這兩種。

程式碼示例

android:tint 著色

<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 而整體變黃。

android:cropToPadding 裁切

<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)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved