views:

68

answers:

2

Hi, I am trying to better understand touches by writing a few liner which which would track touches:

- (void)drawRect:(CGRect)rect {
    NSLog (@"My draw");

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 2);
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);

    CGContextMoveToPoint(context, prev.x, prev.y);
    CGContextAddLineToPoint(context, cur.x, cur.y);
     CGContextStrokePath(context);
    return;
}
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{

UITouch *touch = [touches anyObject];
prev = [touch previousLocationInView:self];
cur = [touch    locationInView:self];

[self setNeedsDisplayInRect:CGRectMake (prev.x, prev.y, fabs (cur.x-prev.x), fabs (cur.y - prev.y) )];
}

It clear that my setNeedsDisplay is not correct, as it only works for movement from positive to negative coordinates (from upper left to lower right). With this questions:

  1. It appears that I have to individually write setNeedsDisplay for 4 different cases of potential movement directions (from pos X, Y to neg X,Y, from pos X to neg X, etc). Is this a correct approach, or I am missing some fundamental piece?

  2. Even for the correct movement the line is not solid, but rather broken (depends on the speed of finger tracking). Why is not is solid line to track movement?

Thanks!

+1  A: 

setNeedsDisplay does not immediately call drawRect. In fact, touchesMoved may be called several times before the next time the view is drawn, which is why you are seeing broken lines.

Ed Marty
A: 

Your call to CGRectMake should be:

CGRectMake (MIN(cur.x, prev.x), MIN (cur.y, prev.y), fabs (cur.x-prev.x), fabs (cur.y - prev.y))

In my code, I generalize this with a function to make a rect from any two points, e.g.:

CGRect rectWithPoints(CGPoint a, CGPoint b)
{
return CGRectMake(
   MIN (a.x, b.x),  
   MIN (a.y, b.y), 
   fabs (a.x - b.x), 
   fabs (a.y - b.y));
}
NSResponder
Thanks, I will give it a try. It still would not help with broken lines, would it?I found some tutorial on the web, which remembers each screen as an image after each line segment and then renders image and adds next set of moves to it. That approach would not need setNeedsDisplay at all.
leon