Search code examples
objective-cuiscrollviewuigesturerecognizerdrawrect

Scrolling with two finger gesture


I have a drawing view on a UIScrollView.

What I want to do is draw lines with one finger, and scrolling with two fingers.

The drawing view is to draw lines through touchesMoved as below.

- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch;
    CGPoint lastTouch, currentTouch;

    for (touch in touches)
    {
        lastTouch = [touch previousLocationInView:self];
        currentTouch = [touch locationInView:self];

        CGContextRef ctx = CGLayerGetContext(drawLayer);
        CGContextBeginPath(ctx);
        CGContextMoveToPoint(ctx, lastTouch.x, lastTouch.y);
        CGContextAddLineToPoint(ctx, currentTouch.x, currentTouch.y);
        CGContextStrokePath(ctx);
    }

    [self setNeedsDisplay];
}

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGContextDrawLayerInRect(drawContext, self.bounds, drawLayer);
    CGContextClearRect(CGLayerGetContext(drawLayer), self.bounds);
    [self setNeedsDisplay];
}

and on a viewController,

    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
    [_scrollView setContentSize:CGSizeMake(320, 800)];
    [self.view addSubview:_scrollView];

    _drawingView = [[DrawingView alloc] initWithFrame:CGRectMake(0, 0, 320, 800)];
    [_scrollView addSubview:_drawingView];

    for (UIGestureRecognizer *gestureRecognizer in _scrollView.gestureRecognizers)
    {
        if ([gestureRecognizer  isKindOfClass:[UIPanGestureRecognizer class]])
        {
            UIPanGestureRecognizer *panGR = (UIPanGestureRecognizer *) gestureRecognizer;
            panGR.minimumNumberOfTouches = 2;
        }
    }

It works ok on simulator however the drawing is too slow on a real device. What is wrong and any suggestion?

Ty!


Solution

  • I solved.

    1. Shouldn't draw whole screen with [self setNeedsDisplay]. Should draw a area where need to redraw with [self setNeedsDisplay withRect:]

    2. Better use panGesture recogniger than touchesBegin~End. There's delay between touchesBegin and touchesEnd.