在前一篇日志中我们已经做好了日历控件的准备工作,今天我们将继续完成这个日历控件。
三、日历元素之Border
在Border类中,我们主要完成日历边框的绘制
package com.xys.mycalender.element; import android.app.Activity; import android.graphics.Canvas; import android.view.View; import com.xys.mycalender.R; import com.xys.mycalender.base.CalendarBase; /* * 绘制日历边框 */ public class Border extends CalendarBase { //日历边框的位置大小 float left; float right; float top; float bottom; public Border(Activity activity, View view) { super(activity, view); // 获取日历边框的颜色 paint.setColor(activity.getResources().getColor(R.color.border_color)); } @Override public void onDraw(Canvas canvas) { left=boderMargin; right=view.getMeasuredWidth()-boderMargin; top=boderMargin; bottom=view.getMeasuredHeight()-boderMargin; // 绘制日历边框 canvas.drawLine(left, top, right, top, paint); canvas.drawLine(left, top, left, bottom, paint); canvas.drawLine(left, bottom, right, bottom, paint); canvas.drawLine(right, top, right, bottom, paint); } }
四、日历元素之Week名称
在Week类中我们主要完成一周名称的绘制
package com.xys.mycalender.element; import android.app.Activity; import android.graphics.Canvas; import android.view.View; import com.xys.mycalender.R; import com.xys.mycalender.base.CalendarBase; /* * 绘制一周的名称 */ public class Week extends CalendarBase { //参数 private float left; private float top; private float eachWeekWidth; private float eachWeekHeight; //一周的名称 private String[] weeknames; //一周名称的颜色1-5 private int weekdayColor; public Week(Activity activity, View view) { super(activity, view); //获取一周名称颜色1-5 weekdayColor=activity.getResources().getColor(R.color.weekname_color); //获取一周名称 weeknames=activity.getResources().getStringArray(R.array.week_name); //设置一周名称大小 paint.setTextSize(weekNameSize); paint.setFakeBoldText(true); } @Override public void onDraw(Canvas canvas) { // TODO Auto-generated method stub left=boderMargin; top=boderMargin; eachWeekWidth=(view.getMeasuredWidth()-boderMargin*2)/7; eachWeekHeight=eachWeekWidth; for (int i = 0; i < weeknames.length; i++) { //周六日 if (i==0||i==weeknames.length-1) { paint.setColor(weekendColor); }else { //平日 paint.setColor(weekdayColor); } //文字绘制在每一格的中间 measureText返回文字的长度 left=boderMargin+eachWeekWidth*i+(eachWeekWidth-paint.measureText(weeknames[i]))/2; top=boderMargin+weekNameMargin+paint.getTextSize(); //开始绘制 canvas.drawText(weeknames[i], left, top, paint); } } }
绘制一周名称的关键在于要将文字绘制在格子的中间,这点的实现见程序倒数2、3行。
时间: 2024-10-24 18:42:06