Reputation: 55564
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
Reputation: 4875
In your custom view:
[self setNeedsDisplay]
so that the view would redrawdrawRect:
, use core graphics to draw a lineLet'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