Search code examples
iphoneiosgesturesswipetouches

How to create and draw a visual swipe gesture


I'd like to try implementing a visual swipe for an iPhone project, like they do in some games, like Fruit Ninja. As you drag your finger around the screen, it leaves a trail that disappears after a while. I would think that you could have a fixed number of points in the "chain" and as new points are added to the front, old ones are removed from the rear. I can see using -touchesMoved to generate new points and an NSMutableArray to keep track of the points. I just can't imaging what method I'd use to actually draw the segments. Would I make one CALayer and draw a line connecting the active points? Or use some other view object and join them together at the points...

Any ideas?


Solution

  • Something like this would work, if you had populated 'points' with CGPoints. Caveat: this is a quick cut, paste and edit job - so there will probably be errors. Also, I use stl::vector for 'points'. You may want to use some other structure.

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGMutablePathRef dataPath = CGPathCreateMutable();
    bool firstPoint = YES;
    
    for (int i=0; i < points.size(); ++i)
        {
        CGPoint point = points[i];
        if (firstPoint)
            {
            CGPathMoveToPoint(dataPath, NULL, point.x, point.y);
            firstPoint = NO;
            }
        else
            {
            CGPathAddLineToPoint(dataPath, NULL, point.x, point.y);
            }
        }
    
    CGContextSetRGBStrokeColor( context, 1.0, 0.0, 0.0, 1.0);
    CGContextSetLineWidth( context, 5);
    CGContextBeginPath( context );
    CGContextAddPath( context, dataPath );
    CGContextDrawPath( context, kCGPathStroke);
    
    CGPathRelease(dataPath);