編輯:關於 Android 程式設計
Class Overview
The Canvas class holds the "draw" calls. To draw something, you need 4 basic components:
A Bitmap to hold the pixels, a Canvas to host the draw calls (writing into the bitmap),
a drawing primitive (e.g. Rect, Path, text, Bitmap), and a paint (to describe the colors
and styles for the drawing).
官方這段說明把要點講得很清楚:要畫東西,你需要四個基本元件——一張存放像素的 Bitmap、一個承載繪製呼叫的 Canvas、一個繪製基元(Rect、Path、文字、Bitmap),以及一支描述顏色與風格的 Paint。
我們可以把 Canvas 理解成系統給我們的一塊畫布,裡面能畫各種東西。更精確地說,它並非記憶體本身(真正的記憶體是 Bitmap),而是一整套對這塊區域進行操作的繪圖 API。也就是說,用這種方式我們已經能一筆一劃地畫出想要的畫面,畫什麼、顯示什麼,完全由自己掌控。
依執行環境不同,這類繪圖大致分成兩種:使用普通 View 的 canvas,以及使用專門的 SurfaceView 的 canvas。主要差別在於 SurfaceView 可以開一條專門的執行緒完成繪製,應用不必等待 View 刷新,效能更好。前者適合資料量小、幀率低的效果(例如象棋這類遊戲);後者主要用在遊戲與高品質動畫。
drawRect(RectF rect, Paint paint) —— 繪製矩形區域,參數一是 RectF 區域。
drawPath(Path path, Paint paint) —— 繪製路徑,參數一是 Path 物件。
drawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint) —— 貼圖。參數一是 Bitmap 物件,參數二是來源區域,參數三是目標區域(決定在 canvas 上的位置與大小),參數四是畫刷。由於可能涉及縮放拉伸,當來源 Rect 不等於目標 Rect 時,效能會有明顯損失。
drawLine(float startX, float startY, float stopX, float stopY, Paint paint) —— 畫線,前四個參數分別是起點 x、起點 y、終點 x、終點 y。
drawPoint(float x, float y, Paint paint) —— 畫點。
drawText(String text, float x, float y, Paint paint) —— 渲染文字。
drawOval(RectF oval, Paint paint) —— 畫橢圓,參數一為掃描區域。
drawCircle(float cx, float cy, float radius, Paint paint) —— 畫圓,依序是圓心 x、圓心 y、半徑、畫筆。
drawArc(RectF oval, float startAngle, float sweepAngle, boolean useCenter, Paint paint) —— 畫弧。參數一界定橢圓形的大小與形狀;參數二是起始角;參數三是順時針掃過的角度;參數四為 true 時連圓心一起封閉(也就是畫出扇形),false 時只畫弧線。
Class Overview
The Paint class holds the style and color information about how to draw geometries,
text and bitmaps.
Paint 攜帶的是「怎麼畫」的資訊——風格與顏色。它代表 Canvas 上的畫筆、畫刷與顏料。常用方法:
setARGB(int a, int r, int g, int b) —— 設定顏色,包含 alpha 透明值。
setAlpha(int a) —— 設定不透明度,範圍 0~255。
setAntiAlias(boolean aa) —— 是否啟用抗鋸齒。
setColor(int color) —— 設定顏色,Color 類已內建常見顏色。
setTextScaleX(float scaleX) —— 文字縮放倍數,1.0f 為原始大小。
setTextSize(float textSize) —— 字級大小。
setUnderlineText(boolean underlineText) —— 是否加底線。
先看效果:

自訂 View 的關鍵是覆寫 onDraw(Canvas),在這個 Canvas 上大量繪製幾何圖形——點、直線、弧、圓、橢圓、文字、矩形、多邊形、曲線、圓角矩形,各種形狀都能畫。
public class CustomActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init() {
LinearLayout layout = (LinearLayout) findViewById(R.id.root);
final DrawView view = new DrawView(this);
view.setMinimumHeight(500);
view.setMinimumWidth(300);
view.invalidate(); // 通知 view 重繪
layout.addView(view);
}
}
public class DrawView extends View {
public DrawView(Context context) { super(context); }
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
/*
* drawRect 繪製矩形 drawCircle 繪製圓形 drawOval 繪製橢圓
* drawPath 繪製多邊形 drawLine 繪製直線 drawPoint 繪製點
*/
Paint p = new Paint();
p.setColor(Color.RED);
canvas.drawText("畫圓:", 10, 20, p);
canvas.drawCircle(60, 20, 10, p); // 小圓
p.setAntiAlias(true); // 去除鋸齒,效果對比明顯
canvas.drawCircle(120, 20, 20, p); // 大圓
canvas.drawText("畫線及弧線:", 10, 60, p);
p.setColor(Color.GREEN);
canvas.drawLine(60, 40, 100, 40, p);
canvas.drawLine(110, 40, 190, 80, p); // 斜線
p.setStyle(Paint.Style.STROKE); // 空心
RectF oval1 = new RectF(150, 20, 180, 40);
canvas.drawArc(oval1, 180, 180, false, p);
oval1.set(190, 20, 220, 40);
canvas.drawArc(oval1, 180, 180, false, p);
oval1.set(160, 30, 210, 60);
canvas.drawArc(oval1, 0, 180, false, p);
canvas.drawText("畫矩形:", 10, 80, p);
p.setColor(Color.GRAY);
p.setStyle(Paint.Style.FILL);
canvas.drawRect(60, 60, 80, 80, p); // 正方形
canvas.drawRect(60, 90, 160, 100, p); // 長方形
canvas.drawText("畫扇形和橢圓:", 10, 120, p);
// 線性漸變,這個形狀的顏色會隨位置變化
Shader mShader = new LinearGradient(0, 0, 100, 100,
new int[] { Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, Color.LTGRAY },
null, Shader.TileMode.REPEAT);
p.setShader(mShader);
RectF oval2 = new RectF(60, 100, 200, 240);
canvas.drawArc(oval2, 200, 130, true, p); // true 畫扇形,false 畫弧線
oval2.set(210, 100, 250, 130);
canvas.drawOval(oval2, p);
canvas.drawText("畫三角形:", 10, 200, p);
Path path = new Path();
path.moveTo(80, 200); // 多邊形起點
path.lineTo(120, 250);
path.lineTo(80, 250);
path.close(); // 封閉
canvas.drawPath(path, p);
p.reset();
p.setColor(Color.LTGRAY);
p.setStyle(Paint.Style.STROKE);
Path path1 = new Path();
path1.moveTo(180, 200);
path1.lineTo(200, 200);
path1.lineTo(210, 210);
path1.lineTo(200, 220);
path1.lineTo(180, 220);
path1.lineTo(170, 210);
path1.close();
canvas.drawPath(path1, p); // 六邊形
p.setStyle(Paint.Style.FILL);
p.setColor(Color.LTGRAY);
p.setAntiAlias(true);
canvas.drawText("畫圓角矩形:", 10, 260, p);
RectF oval3 = new RectF(80, 260, 200, 300);
canvas.drawRoundRect(oval3, 20, 15, p); // 第二、三參數分別是 x、y 半徑
canvas.drawText("畫貝塞爾曲線:", 10, 310, p);
p.reset();
p.setStyle(Paint.Style.STROKE);
p.setColor(Color.GREEN);
Path path2 = new Path();
path2.moveTo(100, 320); // Path 起點
path2.quadTo(150, 310, 170, 400); // 控制點座標 + 終點座標
canvas.drawPath(path2, p);
p.setStyle(Paint.Style.FILL);
canvas.drawText("畫點:", 10, 390, p);
canvas.drawPoint(60, 390, p);
canvas.drawPoints(new float[]{60,400,65,400,70,400}, p);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
canvas.drawBitmap(bitmap, 250, 360, p);
}
}
弧線、填充顏色、Bitmap、圓與橢圓、點、線、矩形、圖片、圓角矩形、文字、頂點、路徑——把這些組合起來已經能做出不少有趣的介面。但如果我想畫一個儀表盤(數字繞著圓圈排布)呢?
幸好 Android 還提供了 rotate、scale、translate、skew(扭曲)等座標轉換方法,也允許你透過 getMatrix() 取得轉換矩陣直接操作。這些操作的直覺是:筆還在原來的位置,但畫紙被旋轉或移動了,於是畫出來的東西方位就變了。為方便搭配使用,Canvas 還提供 save 與 restore——先存下目前畫紙狀態,旋轉 90 度、下移 100 像素畫些圖形,畫完 restore 回到剛才的位置。
drawCircle:
protected void onDraw(Canvas canvas) {
canvas.drawCircle(100, 100, 90, paint);
}

drawArc(useCenter = false,只畫弧線):
@Override
protected void onDraw(Canvas canvas) {
RectF rect = new RectF(0, 0, 100, 100); // 弧線所在的矩形區域
canvas.drawArc(rect,
0, // 起始角度
90, // 掃過的角度
false, // 是否連圓心一起封閉
paint);
}

drawArc(useCenter = true,畫出扇形):
@Override
protected void onDraw(Canvas canvas) {
RectF rect = new RectF(0, 0, 100, 100);
canvas.drawArc(rect, 0, 90, true, paint);
}

drawColor:直接填滿整個 View 顯示區域。
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLUE);
}

drawLine:
@Override
protected void onDraw(Canvas canvas) {
canvas.drawLine(10, 10, 100, 100, paint);
}

drawOval:在矩形區域內畫內切橢圓。
@Override
protected void onDraw(Canvas canvas) {
RectF oval = new RectF(0, 0, 200, 300);
canvas.drawOval(oval, paint);
}

drawPosText:依指定座標逐字繪製。
@Override
protected void onDraw(Canvas canvas) {
canvas.drawPosText("Android777", new float[] {
10, 10, // 第一個字在 10,10
20, 20, // 第二個字在 20,20
30, 30,
40, 40,
50, 50,
60, 60,
70, 70,
80, 80,
90, 90,
100, 100
}, paint);
}

drawRect:參數是左上角與右下角座標。
@Override
protected void onDraw(Canvas canvas) {
RectF rect = new RectF(50, 50, 200, 200);
canvas.drawRect(rect, paint);
}

drawRoundRect:後兩個參數是 x 與 y 方向的圓角半徑。
@Override
protected void onDraw(Canvas canvas) {
RectF rect = new RectF(50, 50, 200, 200);
canvas.drawRoundRect(rect, 30, 30, paint);
}

drawPath:先定義路徑再描繪。
@Override
protected void onDraw(Canvas canvas) {
Path path = new Path();
path.moveTo(10, 10); // 移動到 10,10
path.lineTo(50, 60);
path.lineTo(200, 80);
path.lineTo(10, 10);
canvas.drawPath(path, paint);
}

drawTextOnPath:讓文字沿著路徑排列。
@Override
protected void onDraw(Canvas canvas) {
Path path = new Path();
path.moveTo(10, 10);
path.lineTo(50, 60);
path.lineTo(200, 80);
path.lineTo(10, 10);
canvas.drawTextOnPath("Android777開發者博客", path, 10, 10, paint);
}

座標轉換:translate 與 rotate。
@Override
protected void onDraw(Canvas canvas) {
paint.setAntiAlias(true);
paint.setStyle(Style.STROKE);
// 把原點移動到畫布中央偏上
canvas.translate(canvas.getWidth() / 2, 200);
canvas.drawCircle(0, 0, 100, paint);
// 畫環繞圓圈的路徑文字
canvas.save();
canvas.translate(-75, -75);
Path path = new Path();
path.addArc(new RectF(0, 0, 150, 150), -180, 180);
Paint citePaint = new Paint(paint);
citePaint.setTextSize(14);
citePaint.setStrokeWidth(1);
canvas.drawTextOnPath("https://www.android777.com", path, 28, 0, citePaint);
canvas.restore();
// 畫 60 個刻度,每 6 度一格
Paint tmpPaint = new Paint(paint);
tmpPaint.setStrokeWidth(1);
float y = 100;
int count = 60;
for (int i = 0; i < count; i++) {
canvas.drawLine(0, y, 0, y + 10, tmpPaint);
canvas.rotate(360f / count, 0, 0);
}
}

把常用的 canvas.draw* 都試過之後,我們結合觸摸事件做個能互動的小應用:
public class CanvasDemoActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new CustomView1(this));
}
/** 自訂一個簡單的 View */
class CustomView1 extends View {
Paint paint;
private ArrayList<PointF> graphics = new ArrayList<PointF>();
public CustomView1(Context context) {
super(context);
paint = new Paint();
paint.setColor(Color.YELLOW);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStrokeWidth(3);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
graphics.add(new PointF(event.getX(), event.getY()));
invalidate(); // 重新繪製
return true;
}
@Override
protected void onDraw(Canvas canvas) {
for (PointF point : graphics) {
canvas.drawPoint(point.x, point.y, paint);
}
}
}
}
點擊時會出現一個小點,拖動時則畫出一條由細點組成的虛線:

以上就是 Canvas 繪圖的核心用法。掌握 Canvas 加 Paint 這對搭檔,再加上座標轉換與 save/restore,自訂 View 的世界基本就向你敞開了。
在 Android 應用內瀏覽網頁:WebView 實作教學
有時候我們會希望在應用程式內部直接瀏覽網頁。雖然可以呼叫系統瀏覽器來開啟,但這種方式在許多情境下並不適用——例如想保留自訂的介面風格、需要攔截頁面載入事件,或單純不想跳出
Volley 源碼全解讀:從請求入隊到回調主線程
Volley 這個名字原意是「齊射」,2013 年的 Google I/O 大會上發布,是 Android 平台的網路通訊庫。它把 AsyncHttpClient 的易用
Android View 框架總結(二):焦點機制全解
前言:View 框架寫到第六篇,才發現第二篇居然漏發了——當時在微信公眾號發了卻忘了同步到部落格,關注公眾號的朋友應該都看過,趁今天有空補上。(本文原始碼以 Androi
Android RecyclerView 滑動聯動:評論欄左右移動動畫實作
效果說明 這個實作讓底部評論欄與點讚欄能隨 RecyclerView 滑動而左右移動。當列表往上滑到評論區時,點讚欄移出畫面,評論輸入欄移入;往下回到頂部時,再切回點讚欄