Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Animate a Drawable in a custom view
- public class CheckerBoard extends View {
- public enum State implements Parcelable {
- EMPTY(0), WHITE(1), BLACK(2);
- }
- private final State[][] boardStates = new State[SIZE][SIZE];
- @Override
- protected void onDraw(Canvas canvas) {
- canvas.drawColor(bgColor);
- for (int y = 0; y < SIZE; y++) {
- for (int x = 0; x < SIZE; x++) {
- if ((y % 2 == 0 && x % 2 != 0) || (y % 2 != 0 && x % 2 == 0)) {
- drawRect(x, y, canvas);
- drawPawn(x, y, canvas);
- }
- }
- }
- }
- private void drawRect(int x, int y, Canvas c) {
- }
- private void drawPawn(int x, int y, Canvas c) {
- }
- private void init() {
- setupBoard();
- pawnLinePaint.setStyle(Paint.Style.STROKE);
- wPawnDrawable.getPaint().setColor(wColor);
- wPawnDrawable.getPaint().setShadowLayer(tileSize + 2, 4, 4, Color.GRAY);
- bPawnDrawable.getPaint().setColor(bColor);
- bPawnDrawable.getPaint().setShadowLayer(tileSize + 2, 4, 4, Color.GRAY);
- playerState = startState;
- }
- public boolean onTouchEvent(MotionEvent event) {
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN:
- int x = (int) (event.getX() / tileSize);
- int y = (int) (event.getY() / tileSize);
- if (selection[0] >= 0) { // A tile is already selected
- if (isValidMove(selection[0], selection[1], x, y)) {
- makeMove(x, y);
- clearSelection();
- switchPlayer();
- invalidate();
- }
- } else { // New selection
- if (isValidSelection(x, y)) {
- selection[0] = x;
- selection[1] = y;
- invalidate();
- }
- }
- return true;
- default:
- return super.onTouchEvent(event);
- }
- }
- private void makeMove(int x, int y) {
- // Move the pawn to the new square
- boardStates[y][x] = boardStates[selection[1]][selection[0]];
- // Old square is now empty
- boardStates[selection[1]][selection[0]] = State.EMPTY;
- }
- private void switchPlayer() {
- playerState = playerState == State.WHITE ? State.BLACK : State.WHITE;
- }
- public CheckerBoard(Context context) {
- super(context);
- init();
- }
- public CheckerBoard(Context context, AttributeSet attrs) {
- super(context, attrs);
- init();
- }
- public CheckerBoard(Context context, AttributeSet attrs, int defStyle) {
- super(context, attrs, defStyle);
- init();
- }
- private class Pawn extends ShapeDrawable {
- public Pawn() {
- super(new OvalShape());
- }
- public void drawWithCircles(Canvas canvas, float x, float y){
- super.draw(canvas);
- canvas.drawCircle(x * tileSize + pawnDiameter, y * tileSize + pawnDiameter, pawnDiameter - pawnPadding,
- pawnLinePaint);
- canvas.drawCircle(x * tileSize + pawnDiameter, y * tileSize + pawnDiameter, pawnDiameter - pawnPadding * 6,
- pawnLinePaint);
- canvas.drawCircle(x * tileSize + pawnDiameter, y * tileSize + pawnDiameter, pawnDiameter - pawnPadding * 8,
- pawnLinePaint);
- }
- }
- }
Add Comment
Please, Sign In to add comment