views:

37

answers:

1

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?

A: 

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);
westsider
Cool! So is this in the `-drawRect` method of a `UIView?` Also, I'm not familiar with `stl::vector` - is that some sort of structue?
Steve
Yes, that's right. It would be in -drawRect:. As for stl::vector<>, it's part of the Standard Template Library that is part of C++. Including it in Obj-C adds a couple more issues in terms of setup (mostly changing .m to .mm and adding a couple of #include lines), but the benefits are significant. For example, stl::vector<> gives you mutable arrays, but at a lower level and with much less overhead (expense) than NSMutableArray - which can only contain NSObjects.
westsider
Thanks, @westsider - I don't have it done yet, but I'm on my way. I'm using regular C array of `CGPoints` right now. The `stl` stuff is too far out of my comfort zone at this point. I might try `CFMutableArray` - I think it might be able to take `CGPoints,` and is toll free bridged to `NSMutableArray.`
Steve