Android : Track touch input on canvas

on Saturday, January 31, 2015


I have a game board with 5x5 squares made of canvas drawrect:



protected void onDraw(Canvas canvas) {
for (int rowNo = 0; rowNo < nSquares; rowNo++) {
paint.setColor(((rowNo & 1) == 0) ? colorA : colorB);
for (int colNo = 0; colNo < nSquares; colNo++) {
int left = colNo * squareWidth;
int top = rowNo * squareWidth;

Rect areaRect = new Rect(left, top, left + squareWidth, top + squareWidth);
canvas.drawRect(areaRect, paint);


paint.setColor((paint.getColor() == colorA) ? colorB : colorA);

paint.setTextSize((float)(squareWidth*0.8));

RectF bounds = new RectF(areaRect);
String letter = "A";
bounds.right = paint.measureText(letter, 0, letter.length());
bounds.bottom = paint.descent() - paint.ascent();

bounds.left += (areaRect.width() - bounds.right) / 2.0f;
bounds.top += (areaRect.height() - bounds.bottom) / 2.0f;

canvas.drawText(letter, bounds.left, bounds.top - paint.ascent(), paint);
}
}


I want to track touch input to get the squares the user are touching.. My attempt was



public boolean onTouchEvent(MotionEvent event){

int action = MotionEventCompat.getActionMasked(event);

int x = (int)event.getX();
int y = (int)event.getY();
Log.i(DEBUG_TAG, "Position: (" + x + ", " + y + ")");

int squareTouched = gameBoard.getSquare(x,y);
}


where getSquare is



public int getSquare(int x, int y) {
int row = 0;
int col = 0;
for(int rowNo = 1; rowNo <= nSquares; rowNo++) {
Log.i("Row", "Width: " + squareWidth + " rowNo: " + rowNo + " rowNo*squareW: " + rowNo*squareWidth + " y: " + y);
if(rowNo*squareWidth > y)
{
row = rowNo;
break;
}
}

for (int colNo = 1; colNo <= nSquares; colNo++) {
if(colNo*squareWidth > x)
{
col = colNo;
break;
}
}
Log.i(DEBUG_TAG, "Row: " + row + " Col: " + col);
return (row-1)*nSquares + col;
}


The problem is that the onTouchEvent getX and getY are referring to the screen 0,0, but when I draw the squares 0,0,0,0 is referring to the view origin? Am I right? How can I get the input position relative to the game board view? Could it be a solution to get the view position in the screen and add/subtract this to the tochEvent x- and y position?


0 comments:

Post a Comment