How would I draw a line using canvas if i touch the image using onTouchevent?

860 views Asked by At

How would I draw a line using canvas if i touch the image using onTouchevent .here i am using imageview as a background and position it based on x/Y co-ords? Also, is it possible to check if a line is drawn at those co-ords? Actually if i draw a line ,it would be overlapped the image view.the line should draw image itself inside the layer.how to calculate image x,y position Thanks,

2

There are 2 answers

1
Martin On
public boolean onTouchEvent(MotionEvent event) {
    int eventaction = event.getAction(); 


   int X = (int)(event.getX()); 
   int Y = (int)(event.getY()); 

   switch (eventaction ) {
    case MotionEvent.ACTION_DOWN: 
        canvas.drawLine(X,Y,someOtherX, someOtherY, paint):
            break;
      <snip>
   }

If you want to check if a line is already drawn at coordinates X,Y, then you have to keep a list or Array of the lines you've already drawn with their start/stop coords or slope/intercept and do the algebra. You've got your current line from X,Y to SomeOtherX,Y. It would be a simple process of going through each line and finding where, if at all, the two lines intersect and if they intersect on screen.

0
Martin On

is merely a shorthad ywa of saying there is more code here, but not important to the point you asked.

How to solve for intersection of two lines, say, these two, in slope-intercept form

y = 3x-3
y = 2.3x+4

At the point of intersection they will both have the same y-coordinate value, so we set the equations equal to each other: 3x-3 = 2.3x+4

This gives us an equation in one unknown (x) which we can solve: Re-arrange to get x terms on left 3x - 2.3x = 4+3 Combining like terms 0.7x = 7 Giving x = 10

To find y, simply set x equal to 10 in the equation of either line and solve for y: Equation for a line y = 3x - 3 (Either line will do) Set x equal to 10 y = 30 - 3
Giving y = 27

We now have both x and y, so the intersection point is (10, 27)