Android 繪圖機制基於 **Canvas (畫布) + Paint (畫筆) + Path/Shape (幾何)** 模型。自訂 View 繼承 `View`,覆寫 `onDraw(Canvas)` 即可實現任意 2D 繪製。
public class DrawDemoView extends View {
private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); // 抗鋸齒
public DrawDemoView(Context context) {
super(context);
init();
}
public DrawDemoView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
// 共用 Paint 設定可在這裡預設,onDraw 中再動態調整
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int w = getWidth();
int h = getHeight();
// 1. 繪製實心矩形背景
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.BLUE);
canvas.drawRect(0, 0, w, h, paint);
// 2. 繪製空心矩形邊框
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.RED);
paint.setStrokeWidth(4f);
canvas.drawRect(10, 10, 100, 30, paint);
// 3. 繪製文字
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.GREEN);
paint.setTextSize(48f);
canvas.drawText("Hello Canvas", 10, 80, paint);
// 4. 繪製圖片
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
canvas.drawBitmap(bitmap, 10, 100, paint);
}
}
public class DrawDemoActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 直接將自訂 View 設為內容視圖
setContentView(new DrawDemoView(this));
}
}
| 方法 | 說明 |
|---|---|
| `drawRect(Rect/left,top,right,bottom, paint)` | 矩形 |
| `drawCircle(cx, cy, radius, paint)` | 圓形 |
| `drawOval(RectF, paint)` | 橢圓 |
| `drawRoundRect(RectF, rx, ry, paint)` | 圓角矩形 |
| `drawLine(x1, y1, x2, y2, paint)` | 直線 |
| `drawPath(Path, paint)` | 任意路徑 |
| `drawText(String, x, y, paint)` | 文字 (基線 baseline) |
| `drawBitmap(Bitmap, x, y, paint)` | 圖片 |
| `drawBitmap(Bitmap, srcRect, dstRect, paint)` | 圖片縮放/裁切繪製 |
| `drawArc(RectF, startAngle, sweepAngle, useCenter, paint)` | 弧形/扇形 |
| 設定 | 方法 | 說明 |
|---|---|---|
| 顏色 | `setColor(int)` / `setARGB(a,r,g,b)` | ARGB 32-bit |
| 樣式 | `setStyle(Style.FILL/STROKE/FILL_AND_STROKE)` | 填充/描邊/兩者 |
| 描邊寬度 | `setStrokeWidth(float)` | 單位 px |
| 描邊端點 | `setStrokeCap(Cap.BUTT/ROUND/SQUARE)` | 線條端點形狀 |
| 描邊轉角 | `setStrokeJoin(Join.MITER/ROUND/BEVEL)` | 線條交接形狀 |
| 文字大小 | `setTextSize(float)` | 單位 px (建議用 `sp2px`) |
| 文字對齊 | `setTextAlign(Align.LEFT/CENTER/RIGHT)` | 相對 x 基準點 |
| 抗鋸齒 | `setAntiAlias(true)` / 建構子 `Paint.ANTI_ALIAS_FLAG` | 必開,否則鋸齒明顯 |
| 次像素抗鋸齒 | `setSubpixelText(true)` | 文字邊緣更平滑 |
| 圖層類型 | `setLayerType(LAYER_TYPE_HARDWARE/SOFTWARE/NONE, paint)` | 硬體加速/軟體繪製 |
| 著色器 | `setShader(Shader)` | 漸層、圖片重複、Compose Shader |
| 色彩過濾 | `setColorFilter(ColorFilter)` | ColorMatrix、Lighting、PorterDuff |
| Xfermode | `setXfermode(Xfermode)` | 混合模式 (遮罩、倒影、擦除) |
SumPathEffect)。掌握 `Canvas` + `Paint` + `Path` 三大核心類別、座標變換矩陣、繪製順序 (背景→前景)、物件複用與硬體加速特性,即可實現從簡單圖形到複雜圖表、遊戲畫面、自訂 UI 元件的所有 2D 繪圖需求。進階建議學習 **Jetpack Compose Canvas API** (Declarative 繪圖) 與 **Skia/AGSL** 著色器語言,迎接現代圖形開發範式。