第一步:线条的颜色
在绘制九宫格的时候,需要用到颜色。为了达到颜色的复用。利用xml文件定义:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="shudu_background">#ffe6f0ff</color>
<color name="shudu_hilite">#ffffffff</color>
<color name="shudu_light">#64c6d4ef</color>
<color name="shudu_dark">#6456648f</color>
</resources>
第二步:绘制线条
为了达到绘制的效果,需要一条亮线和一条暗线合二为一。
package com.example.shudu_1;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.v4.view.PagerAdapter;
import android.text.style.LineHeightSpan.WithDensity;
import android.view.View;
public class MyView extends View {
//设置单元格的宽度和高度
private float width;
private float height;
//需要这个构造函数,不然会报错
public MyView(Context context) {
super(context);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
//计算当前单元格的高度和宽度
this.width=w/9f;
this.height=h/9f;
super.onSizeChanged(w, h, oldw, oldh);
}
@Override
protected void onDraw(Canvas canvas) {
//生成用于绘制背景色的画笔
Paint backgroundPaint=new Paint();
//设置背景的颜色
backgroundPaint.setColor(getResources().getColor(R.color.shudu_background));
//绘制背景色
canvas.drawRect(0, 0, getWidth(), getHeight(), backgroundPaint);
Paint darkPain=new Paint();
darkPain.setColor(getResources().getColor(R.color.shudu_dark));
Paint hiliPaint=new Paint();
hiliPaint.setColor(getResources().getColor(R.color.shudu_hilite));
Paint lightPaint=new Paint();
lightPaint.setColor(getResources().getColor(R.color.shudu_light));
for(int i=0;i<9;++i){
//以下两行代码用户绘制横向的单元格
//明线和黑线才能合成一条像雕刻的线,两条线中间有间隔。
canvas.drawLine(0, i*height, getWidth(), i*height,lightPaint);
canvas.drawLine(0, i*height+1, getWidth(), i*height+1,hiliPaint);
//纵向
canvas.drawLine(i*width, 0, i*width, getHeight(), lightPaint);
canvas.drawLine(i*width+1, 0, i*width+1, getHeight(), hiliPaint);
}
//绘制黑线
for(int i=0;i<9;++i){
if(i%3!=0){
continue;
}
//以下两行代码用户绘制横向的单元格
//明线和黑线才能合成一条雕刻的线
canvas.drawLine(0, i*height, getWidth(), i*height,darkPain);
canvas.drawLine(0, i*height+1, getWidth(), i*height+1,hiliPaint);
//纵向
canvas.drawLine(i*width, 0, i*width, getHeight(), darkPain);
canvas.drawLine(i*width+1, 0, i*width+1, getHeight(), hiliPaint);
}
//绘制文字
Paint numberPain=new Paint();
numberPain.setColor(Color.BLACK);
numberPain.setStyle(Paint.Style.STROKE);
numberPain.setTextSize(height*0.75f);
numberPain.setTextAlign(Paint.Align.CENTER);
float x=width/2;
canvas.drawText("1", 3*width+x, 61, numberPain);
super.onDraw(canvas);
}
}