adit adit - 8 months ago 57
iOS Question

drawing dashed line using CALayer

I was able to draw a dashed box, using the following code:

CAShapeLayer *shapeLayer = [CAShapeLayer layer];
CGRect shapeRect = CGRectMake(0.0f, 0.0f, 200.0f, 100.0f);
[shapeLayer setBounds:shapeRect];
[shapeLayer setPosition:CGPointMake(self.coreImageView_.frameX, self.coreImageView_.frameBottom - self.coreImageView_.frameHeight/2)];
[shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
[shapeLayer setStrokeColor:[[UIColor whiteColor] CGColor]];
[shapeLayer setLineWidth:2.0f];
[shapeLayer setLineJoin:kCALineJoinRound];
[shapeLayer setLineDashPattern:
[NSArray arrayWithObjects:[NSNumber numberWithInt:5],
[NSNumber numberWithInt:5],

Now if I want to just draw a dashed line from point X to point B, how should I modify this code?


Lines are drawn by first moving the path to a starting point of the line, then adding a line segment to a point:

CGContextMoveToPoint(context, 10.5f, 10.5f);
CGContextAddLineToPoint(context, 20.5f, 20.5f);
CGContextDrawPath(context, kCGPathFillStroke);

For drawing dashed line, You need to use CAShapeLayer

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, 10, 10);
CGPathAddLineToPoint(path, NULL, 100,100);

[shapeLayer setPath:path];

[[self layer] addSublayer:shapeLayer];