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

自製簽到日曆:用 onDraw 與 Path 打造自定義 CalendarView

編輯:關於 Android 程式設計

前言

這篇文章的看點主要在源碼本身,程式碼裡的註解寫得相當詳細,直接讀源碼反而更好理解。因此本文著重說明組件的整體運作流程,並搭配關鍵程式碼片段來講解。

自定義 View 通常需要重寫三個方法:onMeasure、onLayout 與 onDraw。它們各司其職——onMeasure 負責測量組件的寬高,onLayout 負責擺放子控制項的位置,onDraw 則負責把自定義內容繪製出來。前面幾篇已經用過 onMeasure 與 onLayout,本篇要動手實作的是 onDraw,順便用上 Path 物件。

那麼,為什麼要重複造輪子做一個帶簽到功能的日曆?說白了,是因為自己還沒怎麼真正用過 onDraw,正好拿這個需求來練手。理由不算充分,但過程開心就好。

先看一下最終效果:

這個 CalendarView 對外提供的 API 大致如下:

 String clickLeftMonth(); //上一個月 return String(年-月) String clickRightMonth(); //下一個月 return String(年-月) Surface getSurface(); //獲取整個組件畫圖對象,可進行設置字體顏色等 return Surface String getYearAndmonth(); // 獲得當前應該顯示的年月 return String(年-月) boolean isSelectMore(); //返回是否多選 setSelectMore(boolean flag);//設置是否多選 setFlagData(String[] flags);//設置要進行標記的數據 setOnItemClickListener(OnItemClickListener); //點擊一個日期的回調事件 setWritingFlag(String str); //設置標記字符,默認為簽到

先粗略梳理一下組件跑起來的整體流程:

1. 初始化數據。
2. 測量組件大小,也就是觸發 OnMeasure 方法。
3. 執行 onDraw 進行繪製。

是不是看起來很簡單?下面我們跟著源碼把流程走一遍。

初始化數據

 public CalendarView(Context context) { super(context); // 初始化數據 init(); } public CalendarView(Context context, AttributeSet attrs) { super(context, attrs); // 初始化數據 init(); } /** * 初始化數據 ,初始化事件對象 ,初始化日期格式類對象 ,Surface布局對象初始化 ,獲取屏幕密度比例 ,設置View背景 ,設置觸摸事件 */ private void init() { // 創建一個Date對象並將引用給顯示的月,選擇開始,選擇結束,今天的日期 curDate = selectedStartDate = selectedEndDate = today = new Date(); // 獲取一個日期類對象 calendar = Calendar.getInstance(); // 設置日期 calendar.setTime(curDate); // 創建一個布局路徑 surface = new Surface(this); // 獲取屏幕密度比例 surface.density = getResources().getDisplayMetrics().density; // 給整個控件設置觸摸事件 setOnTouchListener(this); } 

可以看到,組件在實例化時就呼叫了 init 方法,其中出現了 new Surface(),用來創建一個 Surface 物件。我們來看看這個 Surface 類到底做了什麼。

 public void init() { float temp = height / 7f;// 將整個視圖分成了7份,每份所占的高度 monthHeight = 0;// (float) ((temp + temp * 0.3f) * 0.6); weekHeight = (float) ((temp + temp * 0.3f) * 0.5); cellHeight = (height - monthHeight - weekHeight) / 6f; cellWidth = width / 7f; // 創建一個邊框的畫筆並設置其屬性 borderPaint = new Paint(); borderPaint.setColor(cellBorderColor); borderPaint.setStyle(Paint.Style.STROKE); // 邊框的寬度 borderWidth = (float) (0.5 * density); borderWidth = borderWidth < 1 ? 1 : borderWidth; borderPaint.setStrokeWidth(borderWidth); // 創建星期畫筆並設置其屬性 weekPaint = new Paint(); weekPaint.setColor(textWeekColor); weekPaint.setAntiAlias(true); float weekTextSize = weekHeight * 0.6f; weekPaint.setTextSize(weekTextSize); weekPaint.setTypeface(Typeface.DEFAULT_BOLD); // 創建時間畫筆並設置其屬性 datePaint = new Paint(); datePaint.setAntiAlias(true); float cellTextSize = cellHeight * 0.3f; datePaint.setTextSize(cellTextSize); datePaint.setTypeface(Typeface.DEFAULT_BOLD); // 創建一個Path對象用於記錄畫筆所畫的路徑 boxPath = new Path(); // 畫第一行,現在起點是0,0 boxPath.rLineTo(width, 0); // 將起點向下移動一個星期格子的高度 boxPath.moveTo(0, monthHeight + weekHeight); // 畫第二行 boxPath.rLineTo(width, 0); // 循環畫縱線和號數的橫線 for (int i = 1; i < 7; i++) { // 縱線 boxPath.moveTo(i * cellWidth, monthHeight); boxPath.rLineTo(0, height - monthHeight); // 橫線 boxPath.moveTo(0, monthHeight + weekHeight + i * cellHeight); boxPath.rLineTo(width, 0); } // 表格被選擇後使用的畫筆 cellBgPaint = new Paint(); cellBgPaint.setAntiAlias(true); cellBgPaint.setStyle(Paint.Style.FILL); cellBgPaint.setColor(cellSelectBgColor); }

這個類做的事其實不多,一個 init 方法就搞定了:初始化各種畫筆,並動態計算各處的寬高。其中 for 迴圈裡的 boxPath,就是用 Path 物件記錄下整個表格的繪製路徑。

回到 CalendarView 類。組件被實例化之後,接著就會觸發 onMeasure 方法。這個方法沒什麼玄機,就是測量組件、確定它需要多大的寬高。要注意的是,onMeasure 和 onLayout 會各執行兩次,之後才輪到 onDraw。來看看 onDraw 的內容。

onDraw 一開始先呼叫了 calculateDate 方法,這個方法負責動態計算日期。

 /** * 計算日期,計算出上月,這月下月的日期裝入到一個數組裡面進行保存 */ private void calculateDate() { calendar.setTime(curDate); calendar.set(Calendar.DAY_OF_MONTH, 1); int dayInWeek = calendar.get(Calendar.DAY_OF_WEEK); Log.d(TAG, "day in week:" + dayInWeek); int monthStart = dayInWeek; monthStart -= 1; // 以日為開頭-1,以星期一為開頭-2 curStartIndex = monthStart; date[monthStart] = 1; // last month if (monthStart > 0) { calendar.set(Calendar.DAY_OF_MONTH, 0); int dayInmonth = calendar.get(Calendar.DAY_OF_MONTH); for (int i = monthStart - 1; i >= 0; i--) { date[i] = dayInmonth; dayInmonth--; } calendar.set(Calendar.DAY_OF_MONTH, date[0]); } showFirstDate = calendar.getTime(); // this month calendar.setTime(curDate); calendar.add(Calendar.MONTH, 1); calendar.set(Calendar.DAY_OF_MONTH, 0); int monthDay = calendar.get(Calendar.DAY_OF_MONTH); for (int i = 1; i < monthDay; i++) { date[monthStart + i] = i + 1; } curEndIndex = monthStart + monthDay; // next month for (int i = monthStart + monthDay; i < 42; i++) { date[i] = i - (monthStart + monthDay) + 1; } if (curEndIndex < 42) { // 顯示了下一月的 calendar.add(Calendar.DAY_OF_MONTH, 1); } calendar.set(Calendar.DAY_OF_MONTH, date[41]); showLastDate = calendar.getTime(); }

這個方法會動態計算日期:先把上個月剩下的日期填進 date 陣列,再填入當月,最後補上個月開頭的幾天。

那為什麼要放在 onDraw 裡呼叫呢?因為如果只在構造方法裡算一次,之後點擊切換月份時數據就不會更新了;而 onMeasure 和 onLayout 又都會執行兩次,也不合適。所以只能放在每次繪製時計算一次。

再往下,這段程式碼負責繪製星期標題。

 // 畫用於分隔顯示號數的表格框 canvas.drawPath(surface.boxPath, surface.borderPaint); // 星期計算 float weekTextY = surface.monthHeight + surface.weekHeight * 3 / 4f; // 繪制星期1.2.3等字體 for (int i = 0; i < surface.weekText.length; i++) { float weekTextX = i * surface.cellWidth + (surface.cellWidth - surface.weekPaint .measureText(surface.weekText[i])) / 2f; canvas.drawText(surface.weekText[i], weekTextX, weekTextY, surface.weekPaint); }

它先動態算出星期一到星期日各自的位置,再在對應座標上繪製文字。

接下來是繪製被選中格子的背景色,預設就是當月今天的格子。

 /** * @param canvas */ private void drawDownOrSelectedBg(Canvas canvas) { // down and not up if (downDate != null) { drawCellBg(canvas, downIndex, surface.cellDownBgColor); } // selected bg color if (!selectedEndDate.before(showFirstDate) && !selectedStartDate.after(showLastDate)) { int[] section = new int[]{-1, -1}; calendar.setTime(curDate); calendar.add(Calendar.MONTH, -1); findSelectedIndex(0, curStartIndex, calendar, section); if (section[1] == -1) { calendar.setTime(curDate); findSelectedIndex(curStartIndex, curEndIndex, calendar, section); } if (section[1] == -1) { calendar.setTime(curDate); calendar.add(Calendar.MONTH, 1); findSelectedIndex(curEndIndex, 42, calendar, section); } if (section[0] == -1) { section[0] = 0; } if (section[1] == -1) { section[1] = 41; } for (int i = section[0]; i <= section[1]; i++) { drawCellBg(canvas, i, surface.cellSelectBgColor); } } }

之後就是正式繪製日期,也就是把數字填進一個個格子裡。

 for (int i = 0; i < num; i++) { // 這個月的字體顏色 int color = surface.textInstantColor; if (isLastMonth(i)) { // 上個月字體顏色 color = surface.textOtherColor; } else if (isNextMonth(i)) { // 下個月字體顏色 color = surface.textOtherColor; } else if (todayIndex != -1) { // 循環為簽到的日期加標記 int flagLen = flagData == null ? 0 : flagData.length; for (int j = 0; j < flagLen; j++) { if ((date[i] + "").equals(flagData[j])) drawCellFlag(canvas, i, surface.textFlagBgColor, surface.textFlagColor); } // 如果todayIndex不等於-1且等於今天 if (i == todayIndex) { // 今天字體顏色 color = surface.textTodayColor; } } drawCellText(canvas, i, date[i] + "", color); }

這裡特別值得一說的,是加上簽到標記的 drawCellFlag 方法。

 /** * 在格子的右上角進行繪制標簽 * * @param canvas 畫布 * @param index 下標 * @param bgcolor 背景顏色 * @param textcolor 字體顏色 */ private void drawCellFlag(Canvas canvas, int index, int bgcolor, int textcolor) { int x = getXByIndex(index); int y = getYByIndex(index); // 計算一個方格子的上下左右距離組件邊框的距離,以此來推出其坐標 float left = surface.cellWidth * (x - 1) + surface.borderWidth; float top = surface.monthHeight + surface.weekHeight + (y - 1) * surface.cellHeight - surface.borderWidth; float right = left + surface.cellWidth + surface.borderWidth; float botton = top + surface.cellHeight - surface.borderWidth; surface.cellBgPaint.setColor(bgcolor); // 通過Path來記錄路徑,畫一個梯形圖 Path path = new Path(); path.moveTo(right - surface.cellWidth * 2 / 3, top); path.lineTo(right - surface.cellWidth / 4, top); path.lineTo(right, botton - surface.cellHeight * 3 / 4); path.lineTo(right, botton - surface.cellHeight / 3); canvas.drawPath(path, surface.cellBgPaint); // 因為下面的繪制的文字將要進行旋轉因此我將以上Canvas繪制的圖案進行保存,這樣就不會被旋轉給影響到了 canvas.save(); // 將字體進行旋轉40度,以文字開始繪制的坐標點進行旋轉 canvas.rotate((float) 45, right - surface.cellWidth * 3 / 7, botton - surface.cellHeight * 5 / 6); surface.cellBgPaint.setColor(textcolor); // 動態的計算字體大小 float a = surface.cellWidth / 4; float b = surface.cellHeight / 4; float c = (float) Math.sqrt(a * a + b * b); surface.cellBgPaint.setTextSize(c * 3 / 5); surface.cellBgPaint.setTypeface(Typeface.DEFAULT_BOLD); // 繪制文字 canvas.drawText(writingFlag, right - surface.cellWidth * 3 / 7, botton - surface.cellHeight * 5 / 6, surface.cellBgPaint); // 釋放旋轉狀態,恢復sava時的狀態 canvas.restore(); }

這個方法先算出每個格子的 left、right、top、bottom,於是就能推出那個小梯形的四個頂點:

 A(right - surface.cellWidth * 2 / 3, top) B(right - surface.cellWidth / 4, top) C(right, botton - surface.cellHeight * 3 / 4) D(right, botton - surface.cellHeight / 3)

用 Path 物件把這四個點連起來,再交給 canvas 繪製即可。而「簽到」這兩個字的落點,也是用同樣的方式算出來的。注意這裡先用 canvas.save() 保存畫布狀態,旋轉 45 度繪製文字後再 restore() 還原,避免影響到前面畫好的圖形。

好了,大致流程就講到這裡。更細節的部分建議直接看源碼,註解寫得很齊全,你一定看得懂。

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