編輯:Android 開發實例
本文聚焦 Android 中最基礎也最常用的圖片容器——ImageView。除了屬性配置與 scaleType 的各種填充策略,我們還會動手做三件事:把圖片擺進界面、用 Matrix 讓它旋轉縮放、以及從服務器把圖片拉下來顯示。所有環節都配了可運行的示例代碼。
ImageView 直接繼承自 View,顧名思義就是「圖像視圖」。但要特別說明的是,它並不是只能貼圖片:任何 Drawable 對象都能交給它渲染,包括形狀、色彩狀態列表、圖層列表等。它可以放進任何布局容器,並內建了縮放與著色能力。
以下是幾個高頻屬性,每個屬性都有對應的 getter / setter:
其中 scaleType 直接影響視覺效果,值得單獨列清:
先把一張 green.png 放進 drawable 目錄(關於 Android 資源目錄體系,後續文章會專門展開),然後用兩個尺寸不同的 ImageView 對比 center 與 fitCenter 的差異:前者保持原尺寸居中,後者會等比放大填满可用空間。
布局代碼:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
- <TextView
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="scaleType:center,未縮放,在ImageView的中心" />
- <ImageView
- android:id="@+id/imageview1"
- android:layout_width="200dp"
- android:layout_height="100dp"
- android:background="#F00"
- android:scaleType="center"
- android:src="@drawable/green" />
- <TextView
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="scaleType:fitCenter,按比例縮放" />
- <ImageView
- android:id="@+id/imageview2"
- android:layout_width="300dp"
- android:layout_height="200dp"
- android:background="#FFF"
- android:padding="10dp"
- android:scaleType="fitCenter"
- android:src="@drawable/green" />
- </LinearLayout>
改尺寸和改角度是兩條不同的路徑,需要分開看。
改尺寸走的是 View 的通用能力。ImageView 繼承自 View,因此可以直接調用 setLayoutParams(new LinearLayout.LayoutParams(w, h)),這套方法對任何子控件都適用。
改角度則要請出 Matrix。它本質是一個 3×3 的坐標變換矩陣,平移、旋轉、縮放都能在其中完成;使用前必須顯式構造實例。下面的例子放了兩個 SeekBar:一個控制顯示尺寸,一個控制旋轉角度。尺寸上限借助 DisplayMetrics 拿到屏幕寬度,避免圖片被拉得超出屏幕(SeekBar 的用法可參考作者另一篇專文)。
布局代碼:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
- <ImageView
- android:id="@+id/imageview3"
- android:layout_width="200dp"
- android:layout_height="150dp"
- android:scaleType="fitCenter"
- android:src="@drawable/green" />
- <TextView
- android:id="@+id/tv1"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_marginTop="10dp"
- android:text="圖像寬度:240 圖像高度:150" />
- <SeekBar
- android:id="@+id/sbSize"
- android:layout_width="200dp"
- android:layout_height="wrap_content"
- android:layout_marginTop="10dp"
- android:max="240"
- android:progress="120" />
- <TextView
- android:id="@+id/tv2"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_marginTop="10dp"
- android:text="0°" />
- <SeekBar
- android:id="@+id/sbRotate"
- android:layout_width="200dp"
- android:layout_height="wrap_content"
- android:layout_marginTop="10dp"
- android:max="360" />
- </LinearLayout>
實現代碼:
- package com.bgxt.imageviewdemo;
- import android.annotation.SuppressLint;
- import android.app.Activity;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.graphics.Matrix;
- import android.graphics.drawable.BitmapDrawable;
- import android.os.Bundle;
- import android.util.DisplayMetrics;
- import android.widget.ImageView;
- import android.widget.LinearLayout;
- import android.widget.SeekBar;
- import android.widget.SeekBar.OnSeekBarChangeListener;
- import android.widget.TextView;
- @SuppressLint("NewApi")
- public class ChangeImageActivity extends Activity implements
- OnSeekBarChangeListener {
- private int minWidth = 80;
- private ImageView imageView;
- private TextView textview1, textview2;
- Matrix matrix=new Matrix();
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- super.onCreate(savedInstanceState);
- setContentView(R.layout.layout_changeimage);
- imageView = (ImageView) findViewById(R.id.imageview3);
- SeekBar seekbar1 = (SeekBar) findViewById(R.id.sbSize);
- SeekBar seekbar2 = (SeekBar) findViewById(R.id.sbRotate);
- textview1 = (TextView) findViewById(R.id.tv1);
- textview2 = (TextView) findViewById(R.id.tv2);
- //獲取當前屏幕的尺寸,並設置圖片放大的最大尺寸,不能超過屏幕尺寸
- DisplayMetrics dm = new DisplayMetrics();
- getWindowManager().getDefaultDisplay().getMetrics(dm);
- seekbar1.setMax(dm.widthPixels - minWidth);
- seekbar1.setOnSeekBarChangeListener(this);
- seekbar2.setOnSeekBarChangeListener(this);
- }
- @Override
- public void onProgressChanged(SeekBar seekBar, int progress,
- boolean fromUser) {
- if (seekBar.getId() == R.id.sbSize) {
- //設置圖片的大小
- int newWidth=progress+minWidth;
- int newHeight=(int)(newWidth*3/4);
- imageView.setLayoutParams(new LinearLayout.LayoutParams(newWidth, newHeight));
- textview1.setText("圖像寬度:"+newWidth+"圖像高度:"+newHeight);
- } else if (seekBar.getId() == R.id.sbRotate){
- //獲取當前待旋轉的圖片
- Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.green);
- //設置旋轉角度
- matrix.setRotate(progress,30,60);
- //通過待旋轉的圖片和角度生成新的圖片
- bitmap=Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
- //綁定圖片到控件上
- imageView.setImageBitmap(bitmap);
- textview2.setText(progress+"°");
- }
- }
- @Override
- public void onStartTrackingTouch(SeekBar seekBar) {
- // TODO Auto-generated method stub
- }
- @Override
- public void onStopTrackingTouch(SeekBar seekBar) {
- // TODO Auto-generated method stub
- }
- }
關鍵點在 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 常用方法:
數據裝載方面,簡單類型走 Message 的 getData() / setData(),底層是一個 Bundle,提供成套的 getXxx / setXxx。複雜對象則有兩條路:一是讓類實現 Parcelable 或 Serializable,再用 Bundle 的 putParcelable / putSerializable 放入;二是直接掛到 Message 的 obj 字段上,它是 Object 類型,什麼都能裝。
Message 自帶的幾個字段:
下面的示例用隨機數決定走 obj 還是 Bundle 這兩條傳遞路徑(聯網細節可參考作者另一篇 HTTP 專文)。
布局代碼:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
- <Button android:id="@+id/btnInternet" android:layout_width="wrap_content"
- android:layout_height="wrap_content" android:text="下載網絡圖片"/>
- <TextView android:id="@+id/tbMsgType" android:layout_width="match_parent"
- android:layout_height="wrap_content"/>
- <ImageView android:id="@+id/ivInternet" android:layout_width="wrap_content"
- android:layout_height="wrap_content"/>
- </LinearLayout>
實現代碼:
- package com.bgxt.imageviewdemo;
- import java.io.InputStream;
- import java.net.HttpURLConnection;
- import java.util.Random;
- import com.bgxt.httputils.HttpUtils;
- import android.app.Activity;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- import android.view.View;
- import android.widget.Button;
- import android.widget.ImageView;
- import android.widget.TextView;
- import android.widget.Toast;
- public class InternetImageActivity extends Activity {
- private Button btnInternet;
- private ImageView ivInternet;
- private TextView tvMsgType;
- private Handler handler;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_internetimage);
- btnInternet = (Button) findViewById(R.id.btnInternet);
- ivInternet = (ImageView) findViewById(R.id.ivInternet);
- tvMsgType = (TextView) findViewById(R.id.tbMsgType);
- // 定義一個handler,用於接收消息
- handler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- Bitmap bmp = null;
- // 通過消息碼確定使用什麼方式傳遞圖片信息
- if (msg.what == 0) {
- bmp = (Bitmap) msg.obj;
- tvMsgType.setText("使用obj傳遞數據");
- } else {
- Bundle ble = msg.getData();
- ble.get("bmp");
- tvMsgType.setText("使用Bundle傳遞數據");
- }
- // 設置圖片到ImageView中
- ivInternet.setImageBitmap(bmp);
- }
- };
- btnInternet.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- //清空之前獲取的數據
- tvMsgType.setText("");
- ivInternet.setImageBitmap(null);
- //定義一個線程類
- new Thread() {
- @Override
- public void run() {
- try {
- //獲取網絡圖片
- InputStream inputStream = HttpUtils
- .getImageViewInputStream();
- Bitmap bitmap = BitmapFactory
- .decodeStream(inputStream);
- Message msg = new Message();
- Random rd = new Random();
- int ird = rd.nextInt(10);
- //通過一個隨機數,隨機選擇通過什麼方式傳遞圖片信息到消息中
- if (ird / 2 == 0) {
- msg.what = 0;
- msg.obj = bitmap;
- } else {
- Bundle bun = new Bundle();
- bun.putParcelable("bmp", bitmap);
- msg.what = 1;
- msg.setData(bun);
- }
- //發送消息
- handler.sendMessage(msg);
- }catch (Exception e) {
- }
- }
- }.start();
- }
- });
- }
- }
聯網工具類:
- package com.bgxt.httputils;
- import java.io.IOException;
- import java.io.InputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
- public class HttpUtils {
- private final static String URL_PATH = "https://ww4.sinaimg.cn/bmiddle/9e58dccejw1e6xow22oc6j20c80gyaav.jpg";
- public HttpUtils() {
- }
- public static InputStream getImageViewInputStream() throws IOException {
- InputStream inputStream = null;
- URL url = new URL(URL_PATH);
- if (url != null) {
- HttpURLConnection httpURLConnection = (HttpURLConnection) url
- .openConnection();
- httpURLConnection.setConnectTimeout(3000);
- httpURLConnection.setRequestMethod("GET");
- httpURLConnection.setDoInput(true);
- int response_code = httpURLConnection.getResponseCode();
- if (response_code == 200) {
- inputStream = httpURLConnection.getInputStream();
- }
- }
- return inputStream;
- }
- }
別忘了在清單文件中聲明 INTERNET 權限,否則請求會直接失敗。
ImageView 的屬性層面並不複雜,真正需要理解的是 scaleType 的取捨、Matrix 的變換邏輯,以及「子線程聯網 + Handler 回主線程更新 UI」這套在早期 Android 版本中反覆出現的協作模式。掌握這三點,網絡圖片加載這個高頻需求基本就通了。
Android 藍牙開發入門:BluetoothAdapter 與配對裝置管理
藍牙讓兩台裝置之間能無線傳輸資料。Android 平台內建了完整的藍牙框架,讓 App 可以與其他藍牙裝置交換資料。本文示範最基礎的三件事:掃描其他裝置、取得已配對裝置清
AudioManager 實戰:用程式控制鈴聲模式與音量
想要讓 App 直接切換手機的鈴聲模式(正常、靜音、震動),Android 提供了 AudioManager 這個系統服務。本文示範如何取得它、切換模式、讀回目前狀態,並
Android 本地化:讓應用程式適配不同語言環境
Android 應用程式可以在許多不同地區的許多裝置上執行。為了讓應用程式更具互動性,它應該能處理文字、數字、檔案等內容,使其適配應用程式即將使用的語言環境。 本章將說明
Android 示例程式剖析之 Snake 貪吃蛇(一:暫停、繼續、穿牆和全屏)
本文以 Android 內建 Snake 範例為基礎,加入暫停與繼續、穿牆效果,以及全螢幕顯示,適合理解遊戲狀態與視窗設定。暫停與繼續原始範例在遊戲開始後沒有暫停功能。我