編輯:Android 開發實例
Android 讓你能對圖片套用各種處理效果,例如調整亮度、加深暗度、轉成灰階等。做法背後的原理其實很直觀:一張圖片本質上就是二維的像素矩陣,只要逐一取出每個像素的 RGB 值做運算,再寫回去,就能得到全新的影像。
Android 以 Bitmap 類別(位於 android.graphics.Bitmap)代表點陣圖。最常見的做法是從 ImageView 上已載入的 Drawable 取得:
private Bitmap bmp; private ImageView img; img = (ImageView)findViewById(R.id.imageView1); BitmapDrawable abmp = (BitmapDrawable)img.getDrawable();
接著呼叫 BitmapDrawable 的 getBitmap() 取得 Bitmap:
bmp = abmp.getBitmap();
用雙層迴圈掃過寬與高,就能對每個像素做處理:
for(int i=0; i<bmp.getWidth(); i++){
for(int j=0; j<bmp.getHeight(); j++){
int p = bmp.getPixel(i, j);
}
}
getWidth() 與 getHeight() 回傳矩陣的寬與高,getPixel() 則回傳指定座標的像素值。拿到像素之後,就能依需要自由運算,例如用 Color.red()、Color.green()、Color.blue() 拆出各通道數值。
Bitmap 類別還有許多輔助方法:
| 方法 | 說明 |
|---|---|
| copy(Bitmap.Config config, boolean isMutable) | 把這個 Bitmap 的像素複製到新的 Bitmap |
| createBitmap(DisplayMetrics display, int width, int height, Bitmap.Config config) | 建立指定寬高、可變動的 Bitmap |
| createBitmap(int width, int height, Bitmap.Config config) | 建立指定寬高、可變動的 Bitmap |
| createBitmap(Bitmap src) | 從來源 Bitmap 建立不可變的 Bitmap |
| extractAlpha() | 回傳一個保留原圖 alpha 值的新 Bitmap |
| getConfig() | 回傳 Bitmap 的設定,若無則回傳 null |
| getDensity() | 回傳 Bitmap 的密度 |
| getRowBytes() | 回傳每一列像素所占的位元組數 |
| setPixel(int x, int y, int color) | 在座標 (x, y) 寫入指定顏色(Bitmap 必須是可變的) |
| setDensity(int density) | 指定 Bitmap 的密度 |
以下範例建立一個具備三顆按鈕的應用,分別把圖片轉為灰階、提高亮度與降低亮度。
| 步驟 | 說明 |
|---|---|
| 1 | 建立 Android 專案並命名為 ImageEffects,Target SDK 選擇較新版本 |
| 2 | 修改 src/MainActivity.java,加入必要程式碼 |
| 3 | 修改 res/layout/activity_main.xml,加入對應元件 |
| 4 | 修改 res/values/string.xml,補上字串資源 |
| 5 | 執行 App,選擇真機或模擬器安裝並驗證結果 |
主 Activity src/com.yiibai.imageeffects/MainActivity.java:
package com.example.imageeffects;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends Activity {
private ImageView img;
private Bitmap bmp;
private Bitmap operation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView)findViewById(R.id.imageView1);
BitmapDrawable abmp = (BitmapDrawable)img.getDrawable();
bmp = abmp.getBitmap();
}
public void gray(View view){
operation= Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(),bmp.getConfig());
double red = 0.33;
double green = 0.59;
double blue = 0.11;
for(int i=0; i<bmp.getWidth(); i++){
for(int j=0; j<bmp.getHeight(); j++){
int p = bmp.getPixel(i, j);
int r = Color.red(p);
int g = Color.green(p);
int b = Color.blue(p);
r = (int) red * r;
g = (int) green * g;
b = (int) blue * b;
operation.setPixel(i, j, Color.argb(Color.alpha(p), r, g, b));
}
}
img.setImageBitmap(operation);
}
public void bright(View view){
operation= Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(),bmp.getConfig());
for(int i=0; i<bmp.getWidth(); i++){
for(int j=0; j<bmp.getHeight(); j++){
int p = bmp.getPixel(i, j);
int r = Color.red(p);
int g = Color.green(p);
int b = Color.blue(p);
int alpha = Color.alpha(p);
r = 100 + r;
g = 100 + g;
b = 100 + b;
alpha = 100 + alpha;
operation.setPixel(i, j, Color.argb(alpha, r, g, b));
}
}
img.setImageBitmap(operation);
}
public void dark(View view){
operation= Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(),bmp.getConfig());
for(int i=0; i<bmp.getWidth(); i++){
for(int j=0; j<bmp.getHeight(); j++){
int p = bmp.getPixel(i, j);
int r = Color.red(p);
int g = Color.green(p);
int b = Color.blue(p);
int alpha = Color.alpha(p);
r = r - 50;
g = g - 50;
b = b - 50;
alpha = alpha -50;
operation.setPixel(i, j, Color.argb(Color.alpha(p), r, g, b));
}
}
img.setImageBitmap(operation);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
版面配置 res/layout/activity_main.xml:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button1"
android:layout_alignBottom="@+id/button1"
android:layout_alignParentRight="true"
android:layout_marginRight="19dp"
android:onClick="dark"
android:text="@string/dark" />
<Button android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="87dp"
android:layout_marginRight="17dp"
android:layout_toLeftOf="@+id/button3"
android:onClick="gray"
android:text="@string/gray" />
<Button android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button2"
android:layout_alignBottom="@+id/button2"
android:layout_centerHorizontal="true"
android:onClick="bright"
android:text="@string/bright" />
<ImageView android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="114dp"
android:src="@drawable/ic_launcher" />
</RelativeLayout>
字串資源 res/values/string.xml:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">ImageEffects</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> <string name="gray">Gray</string> <string name="bright">bright</string> <string name="dark">dark</string> </resources>
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.yiibai.imageeffects"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" />
<application android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity android:name="com.yiibai.imageeffects.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
執行應用程式,若 AVD 環境設定正確,會看到如下畫面,圖片下方有三顆按鈕:
按下 Gray 按鈕,圖片會轉為灰階並更新畫面:
按下 bright 按鈕,程式會替每個像素加上固定數值,營造出更明亮的視覺效果:
按下 dark 按鈕則相反,每個像素都減去固定數值,畫面因此變暗:
要留意的是,這種逐像素運算完全跑在主執行緒上,圖片一大就會明顯卡頓。實務上若處理的是高解析度照片,建議改用 ColorMatrix 搭配 Canvas,或把運算放到背景執行緒,避免觸發 ANR。
Android 登入介面實作:密碼遮蔽與三次失敗鎖定
登入畫面是使用者與 App 建立信任的第一站。它索取一組憑證,換取進入權限——不論是社群服務、雲端儲存還是企業內部系統,這道關卡都省不掉。 本章要動手做一個登入介面,並把
Android 自訂 Toast:讓提示訊息符合 App 的視覺風格
系統預設的 Toast 簡潔好用,一行 makeText 就能搞定。問題是它長得實在太「系統」了,放在一個講究視覺設計的 App 裡總顯得格格不入。好在 Toast 的樣
Android 開機自啟實作:攔截 BOOT_COMPLETED 廣播
我們有時會希望 App 能在 Android 裝置開機完成後自動啟動,就像 Windows 裡那些常駐程式一樣——例如某些背景 Service 需要定期從網路上更新內容。
Android 手機衛士(十三):實現設置界面的一個條目布局
從本文開始,我們會一步步把功能列表補齊。 一、為九宮格註冊點擊事件 要讓九宮格中的條目可以點擊,得先註冊監聽: // 注冊九宮格單個條目的點擊事件 gv_hom