views:

38

answers:

2

How can I draw a line between one point (the center of one UIView) to a point that moves (touch location), and the line moves the 2nd point as the touch moves.

+4  A: 

In your custom view:

  • in touchesMoved:withEvent store current point into a variable, and call [self setNeedsDisplay] so that the view would redraw
  • implement drawing of a line in drawRect:, use core graphics to draw a line

Let's say you store the touched point into property self.touchedPoint, then drawing might look like this:

@property (nonatomic, assign) CGPoint touchedPoint;

- (void)drawRect:(CGRect)rect
{
 CGContextRef context = UIGraphicsGetCurrentContext();       
 CGContextSaveGState(context);

 CGContextTranslateCTM(context, 0.0, rect.size.height);
 CGContextScaleCTM(context, 1.0, -1.0);

 CGContextSetShouldAntialias(context, YES);
 CGContextSetLineWidth(context, 1.0f);
 CGContextSetRGBStrokeColor(context, 0.7, 0.7, 0.7, 1.0);

 CGContextMoveToPoint(context, rect.size.width/2, rect.size.height/2);
 CGContextAddLineToPoint(context, self.touchedPoint.x, self.touchedPoint.y);
 CGContextDrawPath(context, kCGPathStroke); 

 CGContextRestoreGState(context);
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    self.touchedPoint = [[touches anyObject] locationInView:self];
    [self setNeedsDisplay];
}
Michal
A: 

I voted Michal's answer up. But I would also suggest looking at the Touches sample project. It is easy to get it running - which may be helpful if you are still just putting together your project.

westsider