Wednesday, June 5, 2013

UIBezierPath removeAllPoints example in Objective C (iOS).


UIBezierPath removeAllPoints

Removes all points from the receiver, effectively deleting all subpaths.

- (void)removeAllPoints

UIBezierPath removeAllPoints example.

- (void)drawRect:(CGRect)rect
{
    if (_uipath == NULL)
       _uipath = [[UIBezierPath alloc] init];
    else
        [_uipath removeAllPoints];

    [self drawRect:rect  :self.graphPoints :self.drawingType ];
}

Example of [UIBezierPath removeAllPoints].

 -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{

    [path removeAllPoints];
    [self setNeedsDisplay];
    ctr = 0;
}

UIBezierPath removeAllPoints example.
- (UIBezierPath*)smoothedPathWithGranularity:(NSInteger)granularity
{
    NSMutableArray *points = [(NSMutableArray*)[self pointsOrdered] mutableCopy];

    if (points.count < 4) return [self bezierPath];

    // Add control points to make the math make sense
    [points insertObject:[points objectAtIndex:0] atIndex:0];
    [points addObject:[points lastObject]];

    UIBezierPath *smoothedPath = [self bezierPath];
    [smoothedPath removeAllPoints];

    [smoothedPath moveToPoint:POINT(0)];

    for (NSUInteger index = 1; index < points.count - 2; index++)
    {
        CGPoint p0 = POINT(index - 1);
        CGPoint p1 = POINT(index);
        CGPoint p2 = POINT(index + 1);
        CGPoint p3 = POINT(index + 2);

        // now add n points starting at p1 + dx/dy up until p2 using Catmull-Rom splines
        for (int i = 1; i < granularity; i++)
        {
            float t = (float) i * (1.0f / (float) granularity);
            float tt = t * t;
            float ttt = tt * t;

            CGPoint pi; // intermediate point
            pi.x = 0.5 * (2*p1.x+(p2.x-p0.x)*t + (2*p0.x-5*p1.x+4*p2.x-p3.x)*tt + (3*p1.x-p0.x-3*p2.x+p3.x)*ttt);
            pi.y = 0.5 * (2*p1.y+(p2.y-p0.y)*t + (2*p0.y-5*p1.y+4*p2.y-p3.y)*tt + (3*p1.y-p0.y-3*p2.y+p3.y)*ttt);
            [smoothedPath addLineToPoint:pi];
        }

        // Now add p2
        [smoothedPath addLineToPoint:p2];
    }

    // finish by adding the last point
    [smoothedPath addLineToPoint:POINT(points.count - 1)];

    return smoothedPath;
}

End of UIBezierPath removeAllPoints example article.