这篇文章本身并没有多少要要学习的知识点,只是一种界面制作的方法吧!
主活动中并没有多少东西:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); ChessBoard chesss=new ChessBoard(this); setContentView(chesss); }
接下来就是棋盘类的书写了:
public class ChessBoard extends View { public int w; public int h; ZhiZuo hua; public ChessBoard(Context context) { super(context); w = context.getResources().getDisplayMetrics().widthPixels; h = context.getResources().getDisplayMetrics().heightPixels; hua=new ZhiZuo(this); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(w, h); } @Override protected void onDraw(Canvas canvas) { //绘制线 hua.huaxian(canvas); //绘制棋子 hua.huazi(canvas); invalidate(); } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction()==MotionEvent.ACTION_DOWN){ /// int event=(int)event.GetX() int eventx=(int)event.getX(); int eventy=(int)event.getY(); hua.luozi(eventx,eventy); } return true; } }
最后呢!是具体的线的绘画,和棋子的绘画,还有是否落子的方法实现:
public class ZhiZuo { private int w, h; private final int jianju = 50; private int numline, numcolumn; private Paint paint; private final int radius = 15; private int cx, cy; private int cLine, cColumn; private boolean isBlack; private Listlist; public ZhiZuo(ChessBoard cb) { this.w = cb.w; this.h = cb.h; numline = h / jianju; numcolumn = w / jianju; paint = new Paint(); paint.setColor(Color.BLACK); paint.setStrokeWidth(4); list = new ArrayList (); } public void luozi(int eventx, int eventy) { cColumn = eventx / jianju; cLine = eventy / jianju; int modex = eventx % jianju; int modey = eventy % jianju; if (modex < jianju / 2 && modey < jianju / 2) { } else if (modex > jianju / 2 && modey < jianju / 2) { cColumn += 1; } else if (modex < jianju / 2 && modey > jianju / 2) { cLine += 1; } else if (modex > jianju / 2 && modey > jianju / 2) { cLine += 1; cColumn += 1; } cx = cColumn * jianju; cy = cLine * jianju; for (int i = 0; i < list.size(); i++) { Point p = list.get(i); if (p.x == cx && p.y == cy) { return; } } list.add(new Point(cx, cy)); } public void huaxian(Canvas canvas) { canvas.drawColor(Color.GRAY); paint.setColor(Color.BLACK); int i = 0; for (i = 0; i <= numline; i++) { canvas.drawLine(0, jianju * i, w, jianju*i, paint); } for (i = 0; i <= numcolumn; i++) { canvas.drawLine(jianju * i, 0,jianju*i,h, paint); } } public void huazi(Canvas canvas) { Point p=null; paint.setStyle(Paint.Style.FILL); for (int i = 0; i < list.size(); i++) { paint.setColor(i%2==1?Color.BLACK:Color.WHITE); p=list.get(i); canvas.drawCircle(p.x, p.y, radius, paint); } } }