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

Android 自定義 View 實作仿 GitHub 的提交活躍表格

編輯:關於 Android 程式設計

說明

本文需要一些基礎知識,如 Canvas、Paint、Path、Rect 等類的基本使用,不熟悉的同學可以先學習相關自定義 View 教程,會有很大幫助。

上圖就是 GitHub 的提交表格,直觀來看可分為幾個部分繪製:

(1)各月份的方格,顏色根據提交次數由淺到深變化

(2)右下角的顏色標志,右對齊即可

(3)左邊的星期,原圖從周日畫到周六,我們從周一畫到周日

(4)上面的月份,只畫 1-12 月

(5)點擊時彈出當天提交情況,由一個小三角和圓角矩形組成

需要解決的計算問題:

(1)生成任意一年的所有天,含年月日周、提交次數、色塊顏色、坐標

(2)一年中所有方格的坐標

(3)右下角顏色標志坐標

(4)左邊星期坐標

(5)上面月份坐標

(6)點擊彈出的提示框與文字坐標

生成某年所有天數

每天的信息封裝成一個類:

 /**
 * 封裝每天的屬性,方便在繪制的時候進行計算
 */
 public class Day implements Serializable{
 /**年**/
 public int year;
 /**月**/
 public int month;
 /**日**/
 public int date;
 /**周幾**/
 public int week;
 /**貢獻次數,默認 0**/
 public int contribution = 0;
 /**默認顏色,根據提交次數改變**/
 public int colour = 0xFFEEEEEE;
 /**方格坐標,左上點,右下點,確定矩形范圍**/
 public float startX;
 public float startY;
 public float endX;
 public float endY;
 @Override
 public String toString() {
 return ""+year+"年"+month+"月"+date+"日周"+week+","+contribution+"次";
 }
 }

要繪製表格,先得算出所有的天。從當年 1 月 1 日算到 12 月 31 日,由於星期連續,所以我們需要知道該年 1 月 1 日是周幾(比如 2016 年 1 月 1 日是周 5)。用一個類來實現:

 public class DateFactory {
 /**平年 map,對應月份和天數**/
 private static HashMap<Integer,Integer> monthMap = new LinkedHashMap<>(12);
 /**閏年 map,對應月份和天數**/
 private static HashMap<Integer,Integer> leapMonthMap = new LinkedHashMap<>(12);
 static {
 monthMap.put(1,31);leapMonthMap.put(1,31);
 monthMap.put(2,28);leapMonthMap.put(2,29);
 monthMap.put(3,31);leapMonthMap.put(3,31);
 monthMap.put(4,30);leapMonthMap.put(4,30);
 monthMap.put(5,31);leapMonthMap.put(5,31);
 monthMap.put(6,30);leapMonthMap.put(6,30);
 monthMap.put(7,31);leapMonthMap.put(7,31);
 monthMap.put(8,31);leapMonthMap.put(8,31);
 monthMap.put(9,30);leapMonthMap.put(9,30);
 monthMap.put(10,31);leapMonthMap.put(10,31);
 monthMap.put(11,30);leapMonthMap.put(11,30);
 monthMap.put(12,31);leapMonthMap.put(12,31);
 }
 /**
 * 輸入年份和 1 月 1 日是周幾
 * @param year 年份
 * @param weekday 該年 1 月 1 日為周幾
 * @return 該年 1 月 1 日到 12 月 31 日所有的天數
 */
 public static List<Day> getDays(int year, int weekday) {
 List<Day> days = new ArrayList<>();
 boolean isLeapYear = isLeapYear(year);
 int dayNum = isLeapYear ? 366 : 365;
 Day day;
 int lastWeekday = weekday;
 for (int i = 1; i <= dayNum; i++) {
 day = new Day();
 day.year = year;
 day.week = lastWeekday<= 7 ? lastWeekday : 1;
 int[] monthAndDay = getMonthAndDay(isLeapYear, i);
 day.month = monthAndDay[0];
 day.date = monthAndDay[1];
 lastWeekday = day.week;
 lastWeekday++;
 days.add(day);
 }
 checkDays(days);
 return days;
 }
 public static int[] getMonthAndDay(boolean isLeapYear,int currentDay) {
 HashMap<Integer,Integer> maps = isLeapYear?leapMonthMap:monthMap;
 Set<Map.Entry<Integer,Integer>> set = maps.entrySet();
 int count = 0;
 Map.Entry<Integer, Integer> month = null;
 for (Map.Entry<Integer, Integer> entry : set) {
 count+=entry.getValue();
 if (currentDay<=count){
 month = entry;
 break;
 }
 }
 if (month == null){
 throw new IllegalStateException("未找到所在的月份");
 }
 int day = month.getValue()-(count-currentDay);
 return new int[]{month.getKey(),day};
 }
 public static boolean isLeapYear(int year) {
 return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
 }
 private static void checkDays(List<Day> days) {
 if (days == null) {
 throw new IllegalArgumentException("天數為空");
 }
 if (days.size() != 365 && days.size() != 366) {
 throw new IllegalArgumentException("天數異常:" + days.size());
 }
 }
 }

具體計算邏輯看代碼即可,不太難,這樣就得到了某年的所有天。

繪製天數格子

該 View 較長,需橫屏顯示。為方便起見,這裡不再做 View 的測量計算與自定義屬性,只關注核心邏輯。先定義成員變量:

 /**灰色方格的默認顏色**/
 private final static int DEFAULT_BOX_COLOUR = 0xFFEEEEEE;
 /**提交次數顏色值**/
 private final static int[] COLOUR_LEVEL = new int[]{0xFF1E6823, 0xFF44A340, 0xFF8CC665, 0xFFD6E685, DEFAULT_BOX_COLOUR};
 /**星期**/
 private String[] weeks = new String[]{"Mon", "Wed", "Fri", "Sun"};
 /**月份**/
 private String[] months = new String[]{"Jan", "Feb", "Mar", "Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
 /**默認的 padding**/
 private int padding = 24;
 /**小方格的默認邊長**/
 private int boxSide = 8;
 /**小方格間的默認間隔**/
 private int boxInterval = 2;
 /**所有周的列數**/
 private int column = 0;
 private List<Day> mDays;
 private Paint boxPaint;
 private Paint textPaint;
 private Paint infoPaint;
 private Paint.FontMetrics metrics;
 private float downX;
 private float downY;
 private Day clickDay;

這些變量是慢慢補充的,寫到哪提取到哪。接著初始化數據:

 public GitHubContributionView(Context context, AttributeSet attrs, int defStyleAttr) {
 super(context, attrs, defStyleAttr);
 initView();
 }
 public void initView() {
 mDays = DateFactory.getDays(2016, 5);
 boxPaint = new Paint();
 boxPaint.setStyle(Paint.Style.FILL);
 boxPaint.setStrokeWidth(2);
 boxPaint.setColor(DEFAULT_BOX_COLOUR);
 boxPaint.setAntiAlias(true);
 textPaint = new Paint();
 textPaint.setStyle(Paint.Style.FILL);
 textPaint.setColor(Color.GRAY);
 textPaint.setTextSize(12);
 textPaint.setAntiAlias(true);
 infoPaint = new Paint();
 infoPaint.setStyle(Paint.Style.FILL);
 infoPaint.setColor(0xCC888888);
 infoPaint.setTextSize(12);
 infoPaint.setAntiAlias(true);
 padding = UI.dp2px(getContext(), padding);
 boxSide = UI.dp2px(getContext(), boxSide);
 metrics = textPaint.getFontMetrics();
 }

以 2016 年為例,mDays 就是該年所有天的集合,接下來在 onDraw 裡先畫方格和月份標記:

 /**
 * 畫出 1-12 月方格小塊和上面的月份
 */
 private void drawBox(Canvas canvas) {
 float startX, startY, endX, endY;
 int month = 1;
 for (int i = 0; i < mDays.size(); i++) {
 Day day = mDays.get(i);
 if (i == 0){
 canvas.drawText(months[0],padding,padding-boxSide/2,textPaint);
 }
 if (day.week == 1 && i != 0) {
 column++;
 if (day.month>month){
 month = day.month;
 canvas.drawText(months[month-1],padding+column*(boxSide+boxInterval),padding-boxSide/2,textPaint);
 }
 }
 startX = padding + column * (boxSide + boxInterval);
 startY = padding + (day.week - 1) * (boxSide + boxInterval);
 endX = startX + boxSide;
 endY = startY + boxSide;
 day.startX = startX;
 day.startY = startY;
 day.endX = endX;
 day.endY = endY;
 boxPaint.setColor(day.colour);
 canvas.drawRect(startX, startY, endX, endY, boxPaint);
 }
 boxPaint.setColor(DEFAULT_BOX_COLOUR);
 }

這裡要注意行列的變化與月份坐標的計算。

繪製星期文本

 /**
 * 畫左側的星期
 */
 private void drawWeek(Canvas canvas) {
 float textLength = 0;
 for (String week : weeks) {
 float tempLength = textPaint.measureText(week);
 if (textLength < tempLength) {
 textLength = tempLength;
 }
 }
 canvas.drawText(weeks[0], padding - textLength - 2, padding + boxSide - metrics.descent, textPaint);
 canvas.drawText(weeks[1], padding - textLength - 2, padding + 3 * (boxSide + boxInterval) - metrics.descent, textPaint);
 canvas.drawText(weeks[2], padding - textLength - 2, padding + 5 * (boxSide + boxInterval) - metrics.descent, textPaint);
 canvas.drawText(weeks[3], padding - textLength - 2, padding + 7 * (boxSide + boxInterval) - metrics.descent, textPaint);
 }

繪製顏色深淺標志

 /**
 * 畫出右下角的顏色深淺標志,右對齊所以從右往左畫
 */
 private void drawTag(Canvas canvas) {
 float moreLength = textPaint.measureText("More");
 float lessLength = textPaint.measureText("Less");
 float moreX = padding + (column + 1) * (boxSide + boxInterval) - boxInterval - moreLength;
 float moreY = padding + 8 * (boxSide + boxInterval) + Math.abs(metrics.ascent);
 canvas.drawText("More", moreX, moreY, textPaint);
 float interval = boxSide - 2;
 float leftX = moreX - interval - boxSide;
 float topY = moreY - boxSide;
 float rightX = moreX - interval;
 float bottomY = moreY;
 for (int i = 0; i < COLOUR_LEVEL.length; i++) {
 boxPaint.setColor(COLOUR_LEVEL[i]);
 canvas.drawRect(leftX - i * (boxSide + boxInterval), topY, rightX - i * (boxSide + boxInterval), bottomY, boxPaint);
 }
 canvas.drawText("Less", leftX - 4 * (boxSide + boxInterval) - interval - lessLength, moreY, textPaint);
 }

這樣表格主體就繪製完成了。

處理點擊事件

判斷點擊坐標若落在方格內,就彈出對應文本框:

 @Override
 public boolean onTouchEvent(MotionEvent event) {
 if (MotionEvent.ACTION_DOWN == event.getAction()) {
 downX = event.getX();
 downY = event.getY();
 findClickBox();
 }
 return super.onTouchEvent(event);
 }

判斷是否在方格內:

 /**
 * 判斷是否點擊在方格內
 */
 private void findClickBox() {
 for (Day day : mDays) {
 if (downX >= day.startX && downX <= day.endX && downY >= day.startY && downY <= day.endY) {
 clickDay = day;
 break;
 }
 }
 refreshView();
 }
 private void refreshView() {
 invalidate();
 }

繪製彈出文本框

 /**
 * 畫方格上的文字彈框
 */
 private void drawPopupInfo(Canvas canvas) {
 if (clickDay != null) {
 Path infoPath = new Path();
 infoPath.moveTo(clickDay.startX + boxSide / 2, clickDay.startY + boxSide / 2);
 infoPath.lineTo(clickDay.startX, clickDay.startY);
 infoPath.lineTo(clickDay.endX, clickDay.startY);
 canvas.drawPath(infoPath,infoPaint);
 textPaint.setColor(Color.WHITE);
 String popupInfo = clickDay.toString();
 float infoHeight = metrics.descent - metrics.ascent;
 float infoLength = textPaint.measureText(popupInfo);
 float leftX = (clickDay.startX + boxSide / 2 ) - (infoLength / 2 + boxSide);
 float topY = clickDay.startY-(infoHeight+2*boxSide);
 float rightX = leftX+infoLength+2*boxSide;
 float bottomY = clickDay.startY;
 RectF rectF = new RectF(leftX, topY, rightX, bottomY);
 canvas.drawRoundRect(rectF,4,4,infoPaint);
 canvas.drawText(popupInfo,leftX+boxSide,topY+boxSide+Math.abs(metrics.ascent),textPaint);
 clickDay = null;
 textPaint.setColor(Color.GRAY);
 }
 }

主體邏輯完成後,再開放設置某天提交次數的方法:

 /**
 * 設置某天的次數
 */
 public void setData(int year,int month,int day,int contribution){
 for (Day d : mDays) {
 if (d.year == year && d.month == month && d.date == day){
 d.contribution = contribution;
 d.colour = getColour(contribution);
 break;
 }
 }
 refreshView();
 }
 /**
 * 根據提交次數來獲取顏色值
 */
 private int getColour(int contribution){
 int colour = 0;
 if (contribution <= 0){
 colour = COLOUR_LEVEL[4];
 }
 if (contribution == 1){
 colour = COLOUR_LEVEL[3];
 }
 if (contribution == 2){
 colour = COLOUR_LEVEL[2];
 }
 if (contribution == 3){
 colour = COLOUR_LEVEL[1];
 }
 if (contribution >= 4){
 colour = COLOUR_LEVEL[0];
 }
 return colour;
 }

所有邏輯完成,主要涉及一些坐標計算。完整代碼如下:

 /**
 * 仿 GitHub 的提交活躍表,橫屏使用
 */
 public class GitHubContributionView extends View {
 private final static int DEFAULT_BOX_COLOUR = 0xFFEEEEEE;
 private final static int[] COLOUR_LEVEL = new int[]{0xFF1E6823, 0xFF44A340, 0xFF8CC665, 0xFFD6E685, DEFAULT_BOX_COLOUR};
 private String[] weeks = new String[]{"Mon", "Wed", "Fri", "Sun"};
 private String[] months = new String[]{"Jan", "Feb", "Mar", "Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
 private int padding = 24;
 private int boxSide = 8;
 private int boxInterval = 2;
 private int column = 0;
 private List<Day> mDays;
 private Paint boxPaint;
 private Paint textPaint;
 private Paint infoPaint;
 private Paint.FontMetrics metrics;
 private float downX;
 private float downY;
 private Day clickDay;
 public GitHubContributionView(Context context) {
 this(context, null);
 }
 public GitHubContributionView(Context context, AttributeSet attrs) {
 this(context, attrs, 0);
 }
 public GitHubContributionView(Context context, AttributeSet attrs, int defStyleAttr) {
 super(context, attrs, defStyleAttr);
 initView();
 }
 public void initView() {
 mDays = DateFactory.getDays(2016, 5);
 boxPaint = new Paint();
 boxPaint.setStyle(Paint.Style.FILL);
 boxPaint.setStrokeWidth(2);
 boxPaint.setColor(DEFAULT_BOX_COLOUR);
 boxPaint.setAntiAlias(true);
 textPaint = new Paint();
 textPaint.setStyle(Paint.Style.FILL);
 textPaint.setColor(Color.GRAY);
 textPaint.setTextSize(12);
 textPaint.setAntiAlias(true);
 infoPaint = new Paint();
 infoPaint.setStyle(Paint.Style.FILL);
 infoPaint.setColor(0xCC888888);
 infoPaint.setTextSize(12);
 infoPaint.setAntiAlias(true);
 padding = UI.dp2px(getContext(), padding);
 boxSide = UI.dp2px(getContext(), boxSide);
 metrics = textPaint.getFontMetrics();
 }
 @Override
 protected void onDraw(Canvas canvas) {
 super.onDraw(canvas);
 column = 0;
 canvas.save();
 drawBox(canvas);
 drawWeek(canvas);
 drawTag(canvas);
 drawPopupInfo(canvas);
 canvas.restore();
 }
 private void drawBox(Canvas canvas) {
 float startX, startY, endX, endY;
 int month = 1;
 for (int i = 0; i < mDays.size(); i++) {
 Day day = mDays.get(i);
 if (i == 0){
 canvas.drawText(months[0],padding,padding-boxSide/2,textPaint);
 }
 if (day.week == 1 && i != 0) {
 column++;
 if (day.month>month){
 month = day.month;
 canvas.drawText(months[month-1],padding+column*(boxSide+boxInterval),padding-boxSide/2,textPaint);
 }
 }
 startX = padding + column * (boxSide + boxInterval);
 startY = padding + (day.week - 1) * (boxSide + boxInterval);
 endX = startX + boxSide;
 endY = startY + boxSide;
 day.startX = startX;
 day.startY = startY;
 day.endX = endX;
 day.endY = endY;
 boxPaint.setColor(day.colour);
 canvas.drawRect(startX, startY, endX, endY, boxPaint);
 }
 boxPaint.setColor(DEFAULT_BOX_COLOUR);
 }
 private void drawWeek(Canvas canvas) {
 float textLength = 0;
 for (String week : weeks) {
 float tempLength = textPaint.measureText(week);
 if (textLength < tempLength) {
 textLength = tempLength;
 }
 }
 canvas.drawText(weeks[0], padding - textLength - 2, padding + boxSide - metrics.descent, textPaint);
 canvas.drawText(weeks[1], padding - textLength - 2, padding + 3 * (boxSide + boxInterval) - metrics.descent, textPaint);
 canvas.drawText(weeks[2], padding - textLength - 2, padding + 5 * (boxSide + boxInterval) - metrics.descent, textPaint);
 canvas.drawText(weeks[3], padding - textLength - 2, padding + 7 * (boxSide + boxInterval) - metrics.descent, textPaint);
 }
 private void drawTag(Canvas canvas) {
 float moreLength = textPaint.measureText("More");
 float lessLength = textPaint.measureText("Less");
 float moreX = padding + (column + 1) * (boxSide + boxInterval) - boxInterval - moreLength;
 float moreY = padding + 8 * (boxSide + boxInterval) + Math.abs(metrics.ascent);
 canvas.drawText("More", moreX, moreY, textPaint);
 float interval = boxSide - 2;
 float leftX = moreX - interval - boxSide;
 float topY = moreY - boxSide;
 float rightX = moreX - interval;
 float bottomY = moreY;
 for (int i = 0; i < COLOUR_LEVEL.length; i++) {
 boxPaint.setColor(COLOUR_LEVEL[i]);
 canvas.drawRect(leftX - i * (boxSide + boxInterval), topY, rightX - i * (boxSide + boxInterval), bottomY, boxPaint);
 }
 canvas.drawText("Less", leftX - 4 * (boxSide + boxInterval) - interval - lessLength, moreY, textPaint);
 }
 @Override
 public boolean onTouchEvent(MotionEvent event) {
 if (MotionEvent.ACTION_DOWN == event.getAction()) {
 downX = event.getX();
 downY = event.getY();
 findClickBox();
 }
 return super.onTouchEvent(event);
 }
 private void findClickBox() {
 for (Day day : mDays) {
 if (downX >= day.startX && downX <= day.endX && downY >= day.startY && downY <= day.endY) {
 clickDay = day;
 break;
 }
 }
 refreshView();
 }
 private void refreshView() {
 invalidate();
 }
 private void drawPopupInfo(Canvas canvas) {
 if (clickDay != null) {
 Path infoPath = new Path();
 infoPath.moveTo(clickDay.startX + boxSide / 2, clickDay.startY + boxSide / 2);
 infoPath.lineTo(clickDay.startX, clickDay.startY);
 infoPath.lineTo(clickDay.endX, clickDay.startY);
 canvas.drawPath(infoPath,infoPaint);
 textPaint.setColor(Color.WHITE);
 String popupInfo = clickDay.toString();
 float infoHeight = metrics.descent - metrics.ascent;
 float infoLength = textPaint.measureText(popupInfo);
 float leftX = (clickDay.startX + boxSide / 2 ) - (infoLength / 2 + boxSide);
 float topY = clickDay.startY-(infoHeight+2*boxSide);
 float rightX = leftX+infoLength+2*boxSide;
 float bottomY = clickDay.startY;
 RectF rectF = new RectF(leftX, topY, rightX, bottomY);
 canvas.drawRoundRect(rectF,4,4,infoPaint);
 canvas.drawText(popupInfo,leftX+boxSide,topY+boxSide+Math.abs(metrics.ascent),textPaint);
 clickDay = null;
 textPaint.setColor(Color.GRAY);
 }
 }
 public void setData(int year,int month,int day,int contribution){
 for (Day d : mDays) {
 if (d.year == year && d.month == month && d.date == day){
 d.contribution = contribution;
 d.colour = getColour(contribution);
 break;
 }
 }
 refreshView();
 }
 private int getColour(int contribution){
 int colour = 0;
 if (contribution <= 0){
 colour = COLOUR_LEVEL[4];
 }
 if (contribution == 1){
 colour = COLOUR_LEVEL[3];
 }
 if (contribution == 2){
 colour = COLOUR_LEVEL[2];
 }
 if (contribution == 3){
 colour = COLOUR_LEVEL[1];
 }
 if (contribution >= 4){
 colour = COLOUR_LEVEL[0];
 }
 return colour;
 }
 }

弄個布局測試一下:

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:gravity="center"
 android:orientation="vertical" >
 <com.franky.custom.view.GitHubContributionView
 android:id="@+id/cc_chart"
 android:layout_width="match_parent"
 android:layout_height="match_parent" />
 </LinearLayout>

隨機塞些數據:

 public class MainActivity extends AppCompatActivity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 GitHubContributionView github = (GitHubContributionView) findViewById(R.id.cc_chart);
 github.setData(2016,12,9,2);
 github.setData(2016,11,9,1);
 github.setData(2016,10,5,10);
 github.setData(2016,8,9,3);
 github.setData(2016,4,20,2);
 github.setData(2016,12,13,3);
 github.setData(2016,12,14,3);
 github.setData(2016,2,15,4);
 }
 }

效果如下(GIF 沒錄好,看圖片):

以上就是自定義 View 實現仿 GitHub 提交活躍表格的完整分享,希望對大家有所幫助。如有疑問歡迎留言交流。

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