Wednesday, June 5, 2013

UIBezierPath setLineDash example in Objective C (iOS).

UIBezierPath setLineDash

Sets the line-stroking pattern for the path.

- (void)setLineDash:(const CGFloat *)pattern count:(NSInteger)count phase:(CGFloat)phase

Parameters of [UIBezierPath setLineDash]
A C-style array of floating point values that contains the lengths (measured in points) of the line segments and gaps in the pattern. The values in the array alternate, starting with the first line segment length, followed by the first gap length, followed by the second line segment length, and so on.
The number of values in pattern.
The offset at which to start drawing the pattern, measured in points along the dashed-line pattern. For example, a phase value of 6 for the pattern 5-2-3-2 would cause drawing to begin in the middle of the first gap.

UIBezierPath setLineDash example.

      // Important, otherwise we will be adding multiple sub layers
      if ([[[self layer] sublayers] objectAtIndex:0])
            self.layer.sublayers = nil;

        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        [shapeLayer setBounds:self.bounds];
        [shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
        [shapeLayer setStrokeColor:[[UIColor blackColor] CGColor]];
        [shapeLayer setLineWidth:3.0f];
        [shapeLayer setLineJoin:kCALineJoinRound];
        [shapeLayer setLineDashPattern:
        [NSArray arrayWithObjects:[NSNumber numberWithInt:10],
        [NSNumber numberWithInt:5],nil]];

        // Setup the path
        CGMutablePathRef path = CGPathCreateMutable();
        CGPathMoveToPoint(path, NULL,,;
        CGPathAddLineToPoint(path, NULL,,;

        [shapeLayer setPath:path];

        [[self layer] addSublayer:shapeLayer];

Example of [UIBezierPath setLineDash].
-(void)setSelected:(BOOL) yes_no {
    selected = yes_no;
   if (yes_no == YES) {
        CGFloat dashArray[2];
        dashArray[0] = 5;
        dashArray[1] = 2;
        [self setLineDash:dashArray count:2 phase:0];
       self.pathColor = [self.unselectedColor highlightWithLevel:.5];
   } else {
       [self setLineDash:nil count:2 phase:0];
        self.pathColor = self.unselectedColor;

UIBezierPath setLineDash example.
UIBezierPath *path = [UIBezierPath new];
CGFloat dashArray[3];
dashArray[0] = 8;
dashArray[1] = 3;
dashArray[2] = 8;
[path setLineDash:dashArray count:dashCount phase: 0.0];

End of UIBezierPath setLineDash example article.