1、FontMetrics的使用方法
float y=height/2 - (ascent+descent)/2
Game.java文件:
package com.example.shudu03;
public class Game {
private final String str="360000000"+"004230800"
+"000004200"+"070460003"+"820000014"+"500013020"
+"001900000"+"007048300"+"000000045";
private int shuduku[]=new int[9*9];
public Game() {
shuduku=formPuzzleString(str);
}
//根据九宫格的坐标,返回该坐标所引该填写数据
private int getTile(int x,int y){
return shuduku[y*9+x];
}
//将九宫格坐标的数字转化为String类型
public String getTileString(int x,int y){
int v=getTile(x,y);
if(v==0){
return "";
}
else{
return String.valueOf(v);
}
}
protected int[] formPuzzleString(String str){
int[] shudu=new int[str.length()];
for(int i=0;i<shudu.length;i++){
shudu[i]=str.charAt(i)-'0';
}
return shudu;
}
}
MyView.java文件:
package com.example.shudu03;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.view.View;
public class MyView extends View {
public MyView(Context context) {
super(context);
}
private float width;
private float height;
private Game game=new Game();
@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 paintBackgroud=new Paint();
paintBackgroud.setColor(getResources().getColor(R.color.backgroundColor));
canvas.drawRect(0, 0, getWidth(), getHeight(), paintBackgroud);
//画第一条颜色重的线的画笔
Paint paintOne=new Paint();
paintOne.setColor(getResources().getColor(R.color.oneLine));
//画第二条颜色轻的线的画笔
Paint paintTwo=new Paint();
paintTwo.setColor(getResources().getColor(R.color.twoLine));
//画颜色重的线
Paint paintThree=new Paint();
paintThree.setColor(getResources().getColor(R.color.threeLine));
for(int i=0;i<9;i++){
canvas.drawLine(0, i*height, getWidth(), i*height, paintOne);
canvas.drawLine(0, i*height+1, getWidth(), i*height+1, paintTwo);
canvas.drawLine(i*width, 0, i*width, getHeight(), paintOne);
canvas.drawLine(i*width+1, 0, i*width+1, getHeight(), paintTwo);
}
for(int i=0;i<9;i++){
if(i%3 != 0){
continue;
}
canvas.drawLine(0, i*height, getWidth(), i*height, paintThree);
canvas.drawLine(0, i*height+1, getWidth(), i*height+1, paintTwo);
canvas.drawLine(i*width, 0, i*width, getHeight(),paintThree);
canvas.drawLine(i*width+1, 0, i*width+1, getHeight(), paintTwo);
}
//画数字的画笔
Paint paintData=new Paint();
paintData.setColor(getResources().getColor(R.color.textColor));
paintData.setStyle(Paint.Style.STROKE);
paintData.setTextSize((float) (height*0.75));
paintData.setTextAlign(Paint.Align.CENTER);
FontMetrics fm=paintData.getFontMetrics();
float x=width/2;
float y=height/2-(fm.ascent+fm.descent)/2;
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
canvas.drawText(game.getTileString(i,
j), i*width+x, j*height+y, paintData);
}
}
super.onDraw(canvas);
}
}