Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 學習筆記:Canvas 畫布常用繪製方法整理

編輯:關於 Android 程式設計

Canvas 類承擔了 Android 的整個屏幕繪製流程,裡面積累了不少實用方法:畫路徑、畫區域、貼圖、畫點、畫線、渲染文本應有盡有。官方文檔也提醒,很多方法都有多個重載版本,參數形式更靈活,遇到需求時不妨翻一翻 API 文檔,或者在 Eclipse 裡敲 canvas.draw 然後按 Alt+/ 看提示。

API 參考地址:https://android.toolib.net/reference/android/graphics/Canvas.html

填充整個畫布

// 設置畫布顏色
canvas.drawColor(Color.BLUE);

畫點

// drawPoint(x, y, paint):x、y 為繪製點坐標
canvas.drawPoint(x, y, paint);

// drawPoints(pts, paint):pts 為點坐標數組,兩個一組
float[] pts = { 10, 10, 120, 120, 230, 230, 40, 40, 90, 90 };
canvas.drawPoints(pts, paint);

// drawPoints(pts, offset, count, paint):offset 表示跳過的數據個數,count 為實際繪製個數
canvas.drawPoints(pts, 3, 4, paint);

最後這行的含義是:跳過 pts 的前 3 個數據之後,再取 4 個數據來畫點,也就是 (120, 230) 與 (230, 40) 這兩個點。這裡要注意 offset 和 count 的單位是「數據個數」而不是「點個數」,很容易搞錯。

畫矩形

// drawRect(left, top, right, bottom, paint)
// 前兩個參數是左上角,後兩個參數是右下角

// 直接傳四個坐標
canvas.drawRect(50, 50, 450, 250, paint);

// 傳 Rect 對象
Rect r = new Rect();
r.left   = 50;    // 左邊
r.top    = 50;    // 上邊
r.right  = 450;   // 右邊
r.bottom = 250;   // 下邊
canvas.drawRect(r, paint);

// 傳 RectF 對象可畫圓角矩形
canvas.drawRect(rectF, paint);

還有很多

除了點和矩形,畫圓、橢圓、扇形等各種簡單圖形的方法也都有,平時不用死記,需要的時候查文檔就好。真正難的往往不是 API 本身,而是想清楚要畫在哪、畫多大——那又是另一門功課了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved