編輯:關於 Android 程式設計
佈局檔很簡單,只需要一個 ImageView。
<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" >
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/face" />
</RelativeLayout>
package com.example.pictogether;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.widget.ImageView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView iv = (ImageView) findViewById(R.id.iv);
// 讀入底圖
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.face);
// 建立一張同尺寸的空白畫布
Bitmap alertBitmap = Bitmap.createBitmap(
bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
Canvas canvas = new Canvas(alertBitmap);
Paint paint = new Paint();
// 先畫底圖
canvas.drawBitmap(bitmap, 0, 0, paint);
// 再畫要疊上去的圖
Bitmap ic_luncher = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
canvas.drawBitmap(ic_luncher, 0, 0, paint);
iv.setImageBitmap(alertBitmap);
}
}

Canvas 的繪製順序就是層疊順序:先呼叫的在下層,後呼叫的在上層。這裡先畫底圖 face,再把 ic_launcher 畫在同一個座標 (0, 0),於是後者蓋住前者的左上角區域。
幾個實務上要注意的點:
canvas.drawBitmap(ic_luncher, 50, 50, paint)。paint.setAlpha(128)。Bitmap.Config.RGB_565 降低位深。這個模式可以延伸成浮水印、頭像框、九宮格拼圖等需求,核心三步驟都是:建立目標 Bitmap → 用 Canvas 依序 drawBitmap → setImageBitmap 顯示。
Android 新手入門:客戶端編程思路與學習路線
長期從事服務端開發的工程師轉向 Android 客戶端時,常會感到思維方式差異很大。本文記錄一位服務端開發者學習 Android 的過程與規劃。作者過去做過 CRM、游戲
在 Android 中用 AspectJ 落地 AOP:從原理到完整配置步驟
先把原理說清楚 在 Eclipse 時代,AspectJ 有 AJDT 插件現成可用,編譯器與關鍵字提示都已經集成完畢。但到了 Android Studio,官方並沒有提
ViewAnimator 與其子類 ViewSwitcher:仿 Launcher 的分頁切換
ViewAnimator 繼承自 FrameLayout,特性是「多個子 View 疊在同一個位置,切換時可套用動畫」。它有一個常用的子類 ViewSwitcher,特別
Android 學習筆記(四):Activity 生命週期、啟動模式與最佳實踐
要把 Activity 用好,就必須理解它的生命週期。靈活掌握這些回呼時機,才能寫出資源用得剛好、狀態不丟的程式。 Android 是以任務(Task)來管理 Activ