androidandroid-canvaswordsearchandroid-paint

Drawing only horizontal, vertical and diagonal lines in Android


I'm developing a wordsearch game. Table Layout contains textviews. Textviews display the characters. When the user finds a word in any one of the 8 directions: TopToBottom, BottomToTop, LeftToRight, RightToLeft, TopToBottomRight, BottomToTopLeft, ToptoBottomLeft, BottomToTopRight, I want to display canvas line over the word in the corresponding direction.

I can draw horizontal, vertical and diagonal lines from a starting point to ending point. Starting point is where the user starts to swipe. Ending point is where he stops the swiping.

Check the first three screenshots here

But my problem is that I can also draw other lines between wrong coordinates which are not horizontal, vertical or diagonal lines. See the next three screen shots.

I want to draw only horizontal, vertical and diagonal lines. When ending point is in wrong coordinates, I need to move the ending point to coincide with any one of nearby direction(which is horizontal, vertical or diagonal).


Solution

  • You can find the slope of the line before you draw. Assuming equally sized, evenly spaced letters, and the touch points are at the same position within each letter...

    something over 0 - vertical line
    ±1 - diagonal
    0 - horizontal

    Formula = (p2.y - p1.y)/(p2.x - p1.x)