Reputation: 1512
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:
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?
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!
Upvotes: 0
Views: 433
Reputation: 16857
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));
}
Upvotes: 0
Reputation: 39690
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.
Upvotes: 1