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

Android 應用開發入門(二十三):ImageView 圖片控件完全解析

編輯:Android 開發實例

導讀

本文聚焦 Android 中最基礎也最常用的圖片容器——ImageView。除了屬性配置與 scaleType 的各種填充策略,我們還會動手做三件事:把圖片擺進界面、用 Matrix 讓它旋轉縮放、以及從服務器把圖片拉下來顯示。所有環節都配了可運行的示例代碼。

ImageView 到底是什麼

ImageView 直接繼承自 View,顧名思義就是「圖像視圖」。但要特別說明的是,它並不是只能貼圖片:任何 Drawable 對象都能交給它渲染,包括形狀、色彩狀態列表、圖層列表等。它可以放進任何布局容器,並內建了縮放與著色能力。

以下是幾個高頻屬性,每個屬性都有對應的 getter / setter:

  • android:adjustViewBounds:是否允許控件自調整邊界,以維持圖片原始長寬比。
  • android:maxHeight / android:maxWidth:限制控件的最大高度與最大寬度。
  • android:scaleType:決定圖片如何在控件內部縮放與對齊。
  • android:src:指定要顯示的 Drawable 資源 ID。

其中 scaleType 直接影響視覺效果,值得單獨列清:

  • matrix:以矩陣方式自由變換。
  • fitXY:橫縱各自拉伸,不保留比例,直到填满控件。
  • fitStart:等比縮放後靠左上角對齊。
  • fitCenter:等比縮放後居中對齊。
  • fitEnd:等比縮放後靠右下角對齊。
  • center:居中顯示原始尺寸,不做任何縮放。
  • centerCrop:等比放大到完全鋪滿控件,超出部分裁掉。
  • centerInside:等比縮小到完整裝進控件,多餘留白。

一、圖片的基本顯示

先把一張 green.png 放進 drawable 目錄(關於 Android 資源目錄體系,後續文章會專門展開),然後用兩個尺寸不同的 ImageView 對比 center 與 fitCenter 的差異:前者保持原尺寸居中,後者會等比放大填满可用空間。

布局代碼:

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" 
  3.     android:layout_width="match_parent" 
  4.     android:layout_height="match_parent" 
  5.     android:orientation="vertical" > 
  6.  
  7.     <TextView 
  8.         android:layout_width="match_parent" 
  9.         android:layout_height="wrap_content" 
  10.         android:text="scaleType:center,未縮放,在ImageView的中心" /> 
  11.  
  12.     <ImageView 
  13.         android:id="@+id/imageview1" 
  14.         android:layout_width="200dp" 
  15.         android:layout_height="100dp" 
  16.         android:background="#F00" 
  17.         android:scaleType="center" 
  18.         android:src="@drawable/green" /> 
  19.  
  20.     <TextView 
  21.         android:layout_width="match_parent" 
  22.         android:layout_height="wrap_content" 
  23.         android:text="scaleType:fitCenter,按比例縮放" /> 
  24.  
  25.     <ImageView 
  26.         android:id="@+id/imageview2" 
  27.         android:layout_width="300dp" 
  28.         android:layout_height="200dp" 
  29.         android:background="#FFF" 
  30.         android:padding="10dp" 
  31.         android:scaleType="fitCenter" 
  32.         android:src="@drawable/green" /> 
  33.  
  34.     </LinearLayout> 

二、縮放與旋轉

改尺寸和改角度是兩條不同的路徑,需要分開看。

改尺寸走的是 View 的通用能力。ImageView 繼承自 View,因此可以直接調用 setLayoutParams(new LinearLayout.LayoutParams(w, h)),這套方法對任何子控件都適用。

改角度則要請出 Matrix。它本質是一個 3×3 的坐標變換矩陣,平移、旋轉、縮放都能在其中完成;使用前必須顯式構造實例。下面的例子放了兩個 SeekBar:一個控制顯示尺寸,一個控制旋轉角度。尺寸上限借助 DisplayMetrics 拿到屏幕寬度,避免圖片被拉得超出屏幕(SeekBar 的用法可參考作者另一篇專文)。

布局代碼:

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" 
  3.     android:layout_width="match_parent" 
  4.     android:layout_height="match_parent" 
  5.     android:orientation="vertical" > 
  6.  
  7.     <ImageView 
  8.         android:id="@+id/imageview3" 
  9.         android:layout_width="200dp" 
  10.         android:layout_height="150dp" 
  11.         android:scaleType="fitCenter" 
  12.         android:src="@drawable/green" /> 
  13.  
  14.     <TextView 
  15.         android:id="@+id/tv1" 
  16.         android:layout_width="match_parent" 
  17.         android:layout_height="wrap_content" 
  18.         android:layout_marginTop="10dp" 
  19.         android:text="圖像寬度:240 圖像高度:150" /> 
  20.  
  21.     <SeekBar 
  22.         android:id="@+id/sbSize" 
  23.         android:layout_width="200dp" 
  24.         android:layout_height="wrap_content" 
  25.         android:layout_marginTop="10dp" 
  26.         android:max="240" 
  27.         android:progress="120" /> 
  28.  
  29.     <TextView 
  30.         android:id="@+id/tv2" 
  31.         android:layout_width="match_parent" 
  32.         android:layout_height="wrap_content" 
  33.         android:layout_marginTop="10dp" 
  34.         android:text="0°" /> 
  35.  
  36.     <SeekBar 
  37.         android:id="@+id/sbRotate" 
  38.         android:layout_width="200dp" 
  39.         android:layout_height="wrap_content" 
  40.         android:layout_marginTop="10dp" 
  41.         android:max="360" /> 
  42.  
  43. </LinearLayout> 

實現代碼:

  1. package com.bgxt.imageviewdemo;  
  2.  
  3. import android.annotation.SuppressLint;  
  4. import android.app.Activity;  
  5. import android.graphics.Bitmap;  
  6. import android.graphics.BitmapFactory;  
  7. import android.graphics.Matrix;  
  8. import android.graphics.drawable.BitmapDrawable;  
  9. import android.os.Bundle;  
  10. import android.util.DisplayMetrics;  
  11.  
  12. import android.widget.ImageView;  
  13. import android.widget.LinearLayout;  
  14. import android.widget.SeekBar;  
  15. import android.widget.SeekBar.OnSeekBarChangeListener;  
  16. import android.widget.TextView;  
  17.  
  18. @SuppressLint("NewApi")  
  19. public class ChangeImageActivity extends Activity implements 
  20.         OnSeekBarChangeListener {  
  21.     private int minWidth = 80;  
  22.     private ImageView imageView;  
  23.     private TextView textview1, textview2;  
  24.     Matrix matrix=new Matrix();  
  25.  
  26.     @Override 
  27.     protected void onCreate(Bundle savedInstanceState) {  
  28.         // TODO Auto-generated method stub  
  29.         super.onCreate(savedInstanceState);  
  30.         setContentView(R.layout.layout_changeimage);  
  31.  
  32.         imageView = (ImageView) findViewById(R.id.imageview3);  
  33.         SeekBar seekbar1 = (SeekBar) findViewById(R.id.sbSize);  
  34.         SeekBar seekbar2 = (SeekBar) findViewById(R.id.sbRotate);  
  35.         textview1 = (TextView) findViewById(R.id.tv1);  
  36.         textview2 = (TextView) findViewById(R.id.tv2);  
  37.  
  38.         //獲取當前屏幕的尺寸,並設置圖片放大的最大尺寸,不能超過屏幕尺寸  
  39.         DisplayMetrics dm = new DisplayMetrics();  
  40.         getWindowManager().getDefaultDisplay().getMetrics(dm);  
  41.         seekbar1.setMax(dm.widthPixels - minWidth);  
  42.           
  43.         seekbar1.setOnSeekBarChangeListener(this);  
  44.         seekbar2.setOnSeekBarChangeListener(this);          
  45.     }  
  46.  
  47.     @Override 
  48.     public void onProgressChanged(SeekBar seekBar, int progress, 
  49.             boolean fromUser) {  
  50.             if (seekBar.getId() == R.id.sbSize) {  
  51.                 //設置圖片的大小  
  52.                 int newWidth=progress+minWidth;  
  53.                 int newHeight=(int)(newWidth*3/4);  
  54.                 imageView.setLayoutParams(new LinearLayout.LayoutParams(newWidth, newHeight));  
  55.                 textview1.setText("圖像寬度:"+newWidth+"圖像高度:"+newHeight);  
  56.             } else if (seekBar.getId() == R.id.sbRotate){  
  57.                 //獲取當前待旋轉的圖片  
  58.                 Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.green);  
  59.                 //設置旋轉角度  
  60.                 matrix.setRotate(progress,30,60);  
  61.                 //通過待旋轉的圖片和角度生成新的圖片  
  62.                 bitmap=Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);  
  63.                 //綁定圖片到控件上  
  64.                 imageView.setImageBitmap(bitmap);  
  65.                 textview2.setText(progress+"°");  
  66.             }  
  67.     }  
  68.  
  69.     @Override 
  70.     public void onStartTrackingTouch(SeekBar seekBar) {  
  71.         // TODO Auto-generated method stub  
  72.  
  73.     }  
  74.  
  75.     @Override 
  76.     public void onStopTrackingTouch(SeekBar seekBar) {  
  77.         // TODO Auto-generated method stub  
  78.  
  79.     }  
  80.  
  81. } 

關鍵點在 onProgressChanged 裡:尺寸分支用 setLayoutParams 直接改控件外框,並以 3:4 的比例推算高度;角度分支則先解碼原圖,再用 matrix.setRotate(角度, 圓心x, 圓心y) 生成新位圖,最後交給 setImageBitmap 貼回控件。

三、從網絡加載圖片

移動端的資源不可能全部打包進本地,實時性內容必須聯網獲取。這也是實際項目裡 ImageView 最常被用到的場景。

Android 4.0 之後多了一條硬性規定:網絡訪問不能放在主線程。而另一條規則是:子線程不能直接操作 UI 控件。兩條規則撞在一起,就必須靠消息機制打通。如果你的項目跑在 4.0 以下,則可以直接在主線程裡完成,沒有這層顧慮。

本文的解法是 Thread 負責聯網,Handler 負責把結果送回主線程。Thread 屬於 Java 基礎知識,這裡著重說 Handler。

Handler 承擔兩個職責:

  • 在新建的子線程中發送消息。
  • 在主線程中接收並處理消息。

發送的時機由開發者掌握,接收的時機則由 Android 通過回調驅動:只要重寫 handleMessage(Message),消息到達時系統就會回调它,Message 對象封裝了隨消息傳遞的數據。

Handler 常用方法:

  • void handleMessage(Message msg):處理消息,供重寫。
  • boolean hasMessage(int what):檢查隊列中是否存在指定 what 的消息。
  • sendEmptyMessage(int what):立即發送空消息。
  • sendEmptyMessageDelayed(int what, long delayMillis):延遲發送空消息。
  • sendMessage(Message msg):立即發送消息。
  • sendMessageDelayed(Message msg, long delayMillis):延遲發送消息。

數據裝載方面,簡單類型走 Message 的 getData() / setData(),底層是一個 Bundle,提供成套的 getXxx / setXxx。複雜對象則有兩條路:一是讓類實現 Parcelable 或 Serializable,再用 Bundle 的 putParcelable / putSerializable 放入;二是直接掛到 Message 的 obj 字段上,它是 Object 類型,什麼都能裝。

  • putParcelable(String key, Parcelable value):對象需實現 Parcelable 接口。
  • putSerializable(String key, Serializable value):對象需實現 Serializable 接口。

Message 自帶的幾個字段:

  • int arg1 / int arg2:兩個整數參數位,適合傳簡單值。
  • Object obj:可攜帶任意對象。
  • int what:消息碼,通常用來標識消息來源。

下面的示例用隨機數決定走 obj 還是 Bundle 這兩條傳遞路徑(聯網細節可參考作者另一篇 HTTP 專文)。

布局代碼:

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" 
  3.     android:layout_width="match_parent" 
  4.     android:layout_height="match_parent" 
  5.     android:orientation="vertical" > 
  6.      
  7.      
  8.     <Button android:id="@+id/btnInternet" android:layout_width="wrap_content" 
  9.     android:layout_height="wrap_content" android:text="下載網絡圖片"/> 
  10.     <TextView android:id="@+id/tbMsgType" android:layout_width="match_parent" 
  11.     android:layout_height="wrap_content"/> 
  12.     <ImageView android:id="@+id/ivInternet" android:layout_width="wrap_content" 
  13.     android:layout_height="wrap_content"/> 
  14. </LinearLayout> 

實現代碼:

  1. package com.bgxt.imageviewdemo;  
  2.  
  3. import java.io.InputStream;  
  4. import java.net.HttpURLConnection;  
  5. import java.util.Random;  
  6.  
  7. import com.bgxt.httputils.HttpUtils;  
  8.  
  9. import android.app.Activity;  
  10. import android.graphics.Bitmap;  
  11. import android.graphics.BitmapFactory;  
  12. import android.os.Bundle;  
  13. import android.os.Handler;  
  14. import android.os.Message;  
  15. import android.view.View;  
  16. import android.widget.Button;  
  17. import android.widget.ImageView;  
  18. import android.widget.TextView;  
  19. import android.widget.Toast;  
  20.  
  21. public class InternetImageActivity extends Activity {  
  22.     private Button btnInternet;  
  23.     private ImageView ivInternet;  
  24.     private TextView tvMsgType;  
  25.     private Handler handler;  
  26.  
  27.     @Override 
  28.     protected void onCreate(Bundle savedInstanceState) {  
  29.         // TODO Auto-generated method stub  
  30.         super.onCreate(savedInstanceState);  
  31.         setContentView(R.layout.activity_internetimage);  
  32.  
  33.         btnInternet = (Button) findViewById(R.id.btnInternet);  
  34.         ivInternet = (ImageView) findViewById(R.id.ivInternet);  
  35.         tvMsgType = (TextView) findViewById(R.id.tbMsgType);  
  36.  
  37.         // 定義一個handler,用於接收消息  
  38.         handler = new Handler() {  
  39.             @Override 
  40.             public void handleMessage(Message msg) {  
  41.                 Bitmap bmp = null;  
  42.                 // 通過消息碼確定使用什麼方式傳遞圖片信息  
  43.                     if (msg.what == 0) {  
  44.                       bmp = (Bitmap) msg.obj;  
  45.                       tvMsgType.setText("使用obj傳遞數據");  
  46.                   } else {  
  47.                     Bundle ble = msg.getData();  
  48.                     ble.get("bmp");  
  49.                     tvMsgType.setText("使用Bundle傳遞數據");  
  50.                 }  
  51.                 // 設置圖片到ImageView中  
  52.                 ivInternet.setImageBitmap(bmp);  
  53.                 }  
  54.         };  
  55.  
  56.         btnInternet.setOnClickListener(new View.OnClickListener() {  
  57.             @Override 
  58.             public void onClick(View v) {  
  59.                 //清空之前獲取的數據  
  60.                 tvMsgType.setText("");  
  61.                 ivInternet.setImageBitmap(null);  
  62.                 //定義一個線程類  
  63.                 new Thread() {  
  64.                     @Override 
  65.                     public void run() {  
  66.                     try {  
  67.                            //獲取網絡圖片  
  68.                          InputStream inputStream = HttpUtils 
  69.                              .getImageViewInputStream();  
  70.                          Bitmap bitmap = BitmapFactory 
  71.                              .decodeStream(inputStream);  
  72.                          Message msg = new Message();  
  73.                          Random rd = new Random();  
  74.                          int ird = rd.nextInt(10);  
  75.                          //通過一個隨機數,隨機選擇通過什麼方式傳遞圖片信息到消息中  
  76.                          if (ird / 2 == 0) {  
  77.                             msg.what = 0;  
  78.                             msg.obj = bitmap;  
  79.                          } else {  
  80.                             Bundle bun = new Bundle();  
  81.                             bun.putParcelable("bmp", bitmap);  
  82.                             msg.what = 1;  
  83.                             msg.setData(bun);  
  84.                          }  
  85.                          //發送消息  
  86.                          handler.sendMessage(msg);  
  87.                          }catch (Exception e) {  
  88.  
  89.                          }  
  90.                     }  
  91.                 }.start();  
  92.             }  
  93.         });  
  94.     }  
  95. } 

聯網工具類:

  1. package com.bgxt.httputils;  
  2.  
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.net.HttpURLConnection;  
  6. import java.net.URL;  
  7.  
  8. public class HttpUtils {  
  9.     private final static String URL_PATH = "https://ww4.sinaimg.cn/bmiddle/9e58dccejw1e6xow22oc6j20c80gyaav.jpg";  
  10.  
  11.     public HttpUtils() {  
  12.     }  
  13.  
  14.     public static InputStream getImageViewInputStream() throws IOException {  
  15.         InputStream inputStream = null;  
  16.         URL url = new URL(URL_PATH);  
  17.         if (url != null) {  
  18.             HttpURLConnection httpURLConnection = (HttpURLConnection) url 
  19.                 .openConnection();  
  20.             httpURLConnection.setConnectTimeout(3000);  
  21.             httpURLConnection.setRequestMethod("GET");  
  22.             httpURLConnection.setDoInput(true);  
  23.             int response_code = httpURLConnection.getResponseCode();  
  24.             if (response_code == 200) {  
  25.                 inputStream = httpURLConnection.getInputStream();  
  26.             }  
  27.         }  
  28.         return inputStream;  
  29.     }  
  30. } 

別忘了在清單文件中聲明 INTERNET 權限,否則請求會直接失敗。

小結

ImageView 的屬性層面並不複雜,真正需要理解的是 scaleType 的取捨、Matrix 的變換邏輯,以及「子線程聯網 + Handler 回主線程更新 UI」這套在早期 Android 版本中反覆出現的協作模式。掌握這三點,網絡圖片加載這個高頻需求基本就通了。

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