Reputation: 391
I am writing a program where the user will drag a line from one UILabel
to another. I created a UIView
subclass called DragView, and overrode the drawRect
method. I made the UIView
a subview of the RootController
view. The DragView
is definitely visible, the drawRect
method is definitely being called, but no line is visible.
These are (what I think are) the relevant pieces of code.
//DragView.m
- (void)drawRect:(CGRect)rect
{
if (context == nil)
{
context = UIGraphicsGetCurrentContext();
}
if (_drawLineFlag)
{
CGContextSetLineWidth(context,2.0);
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGFloat components[] = {0.0,0.0,1.0,1.0};
CGColorRef color = CGColorCreate(colorspace, components);
CGContextSetStrokeColorWithColor(context,color);
CGContextMoveToPoint(context,_startX, _startY);
CGContextAddLineToPoint(context,_currentX,_currentY);
CGContextStrokePath(context);
}
}
DrawProgramAppDelegate
- (void) initializeUI
{
.....
dragView = [[DragView alloc] initWithFrame:CGRectMake(0.0f,0.0f,1024.0f,768.0f)] ;
[view addSubview: dragView];
UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
[dragView addGestureRecognizer:panGestureRecognizer];
.....
}
The event handler is:
- (void) handlePan:(UIPanGestureRecognizer *) recognizer
{
CGPoint point = [recognizer translationInView:dragView];
[dragView setCurrentX:point.x];
[dragView setCurrentY:point.y];
[dragView setDrawLineFlag:YES];
[view bringSubviewToFront:drawView];
[dragView drawRect:CGRectMake (0.0f,0.0f,768.0f, 1024.0f)];
}
Many thanks for your help.
Jon
Upvotes: 0
Views: 1635
Reputation: 16827
It seems to me you are trying to draw a path (you should take a look at this post). Here it seems you just draw a line from the last point to the current point
CGContextMoveToPoint(context,_startX, _startY);
CGContextAddLineToPoint(context,_currentX,_currentY);
which given the frequency of the call would only draw a tiny line.
You should not call drawRect:
[dragView drawRect:CGRectMake (0.0f,0.0f,768.0f, 1024.0f)];
You should tell the system the view needs displaying
[dragView setNeedsDisplay];
Also you should check the gesture recognizer state, defined as
typedef enum {
UIGestureRecognizerStatePossible,
UIGestureRecognizerStateBegan,
UIGestureRecognizerStateChanged,
UIGestureRecognizerStateEnded,
UIGestureRecognizerStateCancelled,
UIGestureRecognizerStateFailed,
UIGestureRecognizerStateRecognized = UIGestureRecognizerStateEnded
} UIGestureRecognizerState;
And possibly only draw if the state is UIGestureRecognizerStateChanged
or UIGestureRecognizerStateEnded
Upvotes: 1