Jonathan.
Jonathan.

Reputation: 55564

draw a line from a stationary point to a moving point on iphone

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.

Upvotes: 1

Views: 1201

Answers (2)

Michal
Michal

Reputation: 4875

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];
}

Upvotes: 5

westsider
westsider

Reputation: 4985

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.

Upvotes: 0

Related Questions